我有三个型号
我想在分类映射表中存储书籍及其类别的关系。通过书籍的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,
));
}
它不起作用。请帮忙。
答案 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,
));