yii 如何在更新操作中获取多选复选框数据并将其保存在连接表中

ruarlubt  于 2022-11-09  发布在  其他
关注(0)|答案(1)|浏览(141)

我有两个模型(视频,类别)。在我的视频形式,我正在获取类别(从类别模型),并显示为复选框(注意:视频表中没有类别字段)。每个视频可以有一个或多个类别。我需要将视频类别(将在视频表单中选择)保存在连接表(video_categories)中。我将使用视频模型中的afterSave()保存类别。我的主要问题是,如何从VideoController的updateAction()中的视频表单中获取我选中的类别,并将它们分配给某个公共成员(视频模型),然后在afterSave()中使用该成员将类别保存在连接表(video_categories)中。* 还有一件事是,我只想将类别保存在updateAction()中。在createAction()中,我只保存视频文件。有关视频的所有其他详细信息都需要保存在updateAction()中。*
这就是我如何在视频窗体中显示类别。

<ul class="catgss_list">
<?php 
$category = common\models\Category::find()->all(); 
foreach($category as $cat):
?>
<li>
    <div class="chekbox-lg">
        <label>
            <input type="checkbox" name="category[]" value="<?php echo $cat->id ?>">
            <b class="checkmark"></b>
            <span><?= $cat->category_name ?></span>
        </label>
    </div>
</li>
<?php endforeach; ?>
</ul>

这就是我的表单https://ibb.co/tpZXrVw的外观

xriantvc

xriantvc1#

我已经解决了我的问题。我所做的是写在下面:-我的视频模型

public $categories;// i declare a public attribute. 
public function afterSave($insert, $changedAttributes) {
    parent::afterSave($insert, $changedAttributes);
    $this->deleteExistingCategories();
    if (isset($_POST['Video']['categories'])) {
        $this->saveVideoCategories($_POST['Video']['categories']);
    }
}

public function deleteExistingCategories() {
    VideoCategory::deleteAll(['video_id' => $this->video_id]);
}

public function saveVideoCategories($categoriesList) {
  foreach ($categoriesList as $category) {
      $videoCategory = new VideoCategory();
      $videoCategory->video_id = $this->video_id;
      $videoCategory->category_id = $category;
      $videoCategory->save();
  }
}

我的视频格式代码

<ul class="catgss_list">
<?php
$checkedCategories = VideoCategory::findAll(['video_id' => $model->video_id]);
if (isset($checkedCategories)) {
    foreach ($checkedCategories as $selectedCategory) {
        $savedCategories[] = $selectedCategory->category_id;
    }
}
$category = Category::find()->all();
foreach ($category as $cat):
?>
<li>
    <div class="chekbox-lg">
        <label>
            <input type="checkbox" name="Video[categories][]" value="<?php echo $cat->id ?>" 
            <?php
            if (isset($savedCategories)) {
                $isCategory = in_array($cat->id, $savedCategories);
                if (isset($isCategory) && $isCategory == true) {
                    echo "checked";
                }
            }
            ?>
                   >
            <b class="checkmark"></b>
            <span><?php echo $cat->category_name ?></span>
        </label>
    </div>
</li>
<?php endforeach; ?>
</ul>

相关问题