通过复选框实现多对多关系


Implementing many_to_many relation with checkboxes

我被困在一些事情上,我认为这是我对多对多关系的经验不足。

在我的应用程序中,我将兴趣映射到具有多对多的产品。我希望创建以下场景,其中在带有复选框的特定产品下列出兴趣的完整列表。对于提交表单时选中的每个复选框,将向InterestProductAssignment表中添加一行。

在我的产品控制器中,我调用完整的兴趣列表-

$interests = Interest::model()->findAll();

实际上,我没有得到太多比这更远的,因为我的头脑在打结,不知道从这里开始。到目前为止,我所尝试的是构建一个InterestProductAssignment对象数组,以匹配我在上面返回的兴趣数组。我试过把它传递给视图和构建出来的形式,但我已经得到了自己相当困惑,试图匹配这两个,我不敢相信我正确地使用Yii,因为它是混乱的。

有谁能提出一个解决这个问题的方案,使我能够对每个兴趣都有一个复选框,在提交时添加产品和兴趣之间的链接?我很想看看你会在控制器和视图中写些什么。

澄清一下,本页只是一个产品的主题。

<<p> 扩展/strong>

对于我所遇到的补充问题,我发布了我所得到的代码,这也可以帮助其他人实现类似的事情,一旦我们发现错误。

我的产品控制器中的关系是这样的-

            'interests'=>array(self::MANY_MANY, 'Interest', 'interest_product_assignment(interest_id, product_id)')
控制器

    public function actionUpdate($id)
{
            // loadModel as been adapted to be called "->with('interests')"
    $model=$this->loadModel($id);
    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);
    if(isset($_POST['Product']))
    {
        $model->attributes=$_POST['Product'];
        if($model->save())
            foreach($_POST['ProductInterest'] as $i => $interest_id){
                $this_interest = new InterestProductAssignment;
                $this_interest->product_id = $model->id;
                $this_interest->interest_id = $interest_id;
                $this_interest->save();
            }
            $this->redirect(array('view','id'=>$model->id));
    }
    $this->render('update',array(
        'model'=>$model,
    ));
}

view_form .php的相关部分

<div class="row">
    <?php echo CHtml::checkBoxList('ProductInterest', CHtml::listData($model->interests, 'interest_id', true), CHtml::listData(Interest::model()->findAll(), 'id', 'interest'));?>
</div>

问题是checkBoxList中的第二个字段似乎没有正确地填充已经选中的复选框。我怀疑这一切的根本原因可能是一个愚蠢的错误。但是我不能发现它,而且我对checkBoxList不够熟悉。

鹅,

我想你在这里找的是CheckBoxList。

在表单中可以使用代码

echo CHtml::checkBoxList('Product_Interests', $model->getInterests(), CHtml::listData(Interest::model()->findAll(), 'interest_id', 'interest_title'));
//$model->getInterests() is a method that should returns an array of IDs of all the currently selected interests

然后在你的控制器中你可以使用代码:

foreach($_POST['Product_Interests'] as $interest_id=>$checked)
    if($checked)
      $model->addInterest($interest_id); //Add Interest
    else
      $model->removeInterest($interest_id); //Remove an Interest if it exists
//Note: If you have a model that connects these tables those can be created or destroyed here