【问题标题】:Yii : Using Two models in single FormYii:在一个表单中使用两个模型
【发布时间】:2014-09-17 12:45:06
【问题描述】:

我有一个三个模型

  1. 书籍
  2. 类别
  3. 类别映射

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

喜欢

Book Name: ______________

Book Author: ______________

Book Published:  _____________

Categories---------------------------------------------

[] Educational  [] Academic [] Spiritual []Self Help   

-------------------------------------------------------

(Save)

例如: 在类别映射表中

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,
        ));
    }

它不工作。请帮忙。

【问题讨论】:

  • 打印$category->getErrors();$model->getErrors();如果保存不成功的条件。
  • 不应该将 $category->save(); 写在 foreach 循环中。为什么要写$category[] = $category;
  • 我试图一次保存所有内容,正如 yii 应用程序开发书中给出的那样
  • 然后你需要再次循环它们并保存它们。无论如何,$category 变量不能在 foreach 之外使用。
  • 这是个好主意,但在哪里使用 $category = new Category();因为我们需要以相同的形式呈现。如果放在开头会有问题,如果我们把它放在 foreach 中,那么在渲染时就会出现问题。

标签: php yii model


【解决方案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,
));

【讨论】:

  • 如果我们在里面使用$category = new Category(); 那么如何将它渲染成表格
  • 您希望在表单中显示选定的类别?如果是,那么您是否需要像 findall 这样的简单数组或对象?视图中的代码可以在此处提供有关类别的更多信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-30
相关资源
最近更新 更多