Reputation: 379
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.
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
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.
Upvotes: 0
Views: 52
Reputation: 1274
When a Book is saved, you wish to save the Categories for it in the Category Mapping
table.
Lets say that the Model for it is 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,
));
Upvotes: 1