Yii:使用单一形式的两个模型

时间:2014-09-17 12:45:07

标签: php yii model

我有三个型号

  1. 图书
  2. 分类
  3. 类别映射
  4. 我想在分类映射表中存储书籍及其类别的关系。通过书籍的checkboxlist中的yii使用Form获取类别的详细信息。

    喜欢

    Book Name: ______________
    
    Book Author: ______________
    
    Book Published:  _____________
    
    Categories---------------------------------------------
    
    [] Educational  [] Academic [] Spiritual []Self Help   
    
    -------------------------------------------------------
    
    (Save)
    

    对于Eg: 在类别映射表

    Book ID | Category ID 
       1    |      2      
       1    |      5
       1    |      7
       2    |      2
    

    controller/Book.php

    public function actionCreate()
        {
            $model=new Book;
    
            if(isset($_POST['Book']))
            {
    
               $bid=$model->book_id;
                if(isset($_POST['Category'])){
    
                    foreach ($_POST['Category'] as $category) {
                        $category = new Category();
                        $category->attributes=$_POST['Category'];
                        $category->map_book_id=$bid;
                        $category[] = $category;
                    }
                    if(!empty($category)){
                        $category->save();
                    }
                }
    
                if($model->save()){
    
                    $this->redirect(array('view','id'=>$model->book_id));
                }
    
            }
    
            $this->render('create',array(
                'model'=>$model,
                'category'=>$category,
            ));
        }
    

    它不起作用。请帮忙。

1 个答案:

答案 0 :(得分:1)

保存图书时,您希望将其类别保存在Category Mapping表格中。

让我们说它的模型是CategoryMapping

尝试 -

//After saving the Book, you have the Book Id in `$bid` variable.

$category_arr = array();

if(isset($_POST['Category'])){

    foreach ($_POST['Category'] as $category) {
        $category_map = new CategoryMapping();
        $category_map->category_id = $category;
        $category_map->book_id = $bid;

        //..... some other attributes to set

        if($category_map->save()) {
            $category_arr[] = $category;
        } else {
            print_r($category_map->getErrors());    //Just for debugging
        }
    }

}

然后 -

$this->render('create',array(
    'model'=>$model,
    'category'=>$category_arr,
));