[英]Yii : Using Two models in single Form
I have a Three models 我有三个模型
I want to store relation of books and their categories in Category mapping Table. 我想将书籍及其类别的关系存储在类别映射表中。 By getting the details of categories using
checkboxlist
in yii in the the Form
of Books. 通过使用图书
Form
的yii中的checkboxlist
来获取类别的详细信息。
Like 喜欢
Book Name: ______________
Book Author: ______________
Book Published: _____________
Categories---------------------------------------------
[] Educational [] Academic [] Spiritual []Self Help
-------------------------------------------------------
(Save)
For Eg: In Category mapping Table 例如:在类别映射表中
Book ID | Category ID
1 | 2
1 | 5
1 | 7
2 | 2
In the controller/Book.php
在
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,
));
}
It is not working. 它不起作用。 Please help.
请帮忙。
When a Book is saved, you wish to save the Categories for it in the Category Mapping
table. 保存书籍后,您希望将其类别保存在
Category Mapping
表中。
Lets say that the Model for it is CategoryMapping
. 可以说它的模型是
CategoryMapping
。
Try - 尝试-
//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
}
}
}
Then - 然后 -
$this->render('create',array(
'model'=>$model,
'category'=>$category_arr,
));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.