问题
Saving articles_categories according to normalization
I have three tables
-----------
articles
-----------
id int(11)
title varchar(100)
-----------
categories
----------
id int(11)
title varchar(100)
-------------------
articles_categories
--------------------
articles_id int(11)
categories_id int(11)
I want to save it according to normalization rule to achieve like this
articles_id | categories_id
1 1
1 2
1 3
How can I achieve with code igniter thanks. So far I had already tried like this
View | Create.php
<?php echo form_input('title','','id="title_input"'); ?><br>
Category
<?php
foreach ($categories as $c)
{
echo '<input type="checkbox" id="categories[]" name="categories[]" value="'.$c['id'].'">';
echo $c['title'].' ';
}
?>
<?php
echo form_submit('Submit',"Submit");
echo form_close();
?>
Controller | articles.php
function insert()
{
$this->articles_model->save();
}
Model | articles_model.php
function save(){
$title=$this->input->post('title');
$categories= implode(',',$_POST['categories']); //inputs will be 1,2,3
$data=array(
/* missing ideas.............*/
);
$this->db->insert('articles_categories',$data);
}
Any help is appreciated. Thanks
回答1:
Ok so you need to first save your article and use $this->db->insert_id()
to get the id of it.
$title = $this->input->post('title');
$data = array('title' => $title);
$this->db->insert('articles', $data);
$article_id = $this->db->insert_id();
Now create a batch operation to insert that id against each of the categories (don't use implode!)
$categories = $this->input->post('categories');
$data = array();
foreach($categories as $category_id){
$data[] = array(
'articles_id' => $article_id,
'categories_id' => $caregory_id
);
}
$this->db->insert_batch('articles_categories', $data);
Hope that helps!
来源:https://stackoverflow.com/questions/16733325/saving-articles-and-related-categories-according-to-normalization