问题
I've got a multiple select for my product categories and I have 3 tables for them. My tables look like:
products:
product_id | product_name
1 | my_package
categories:
category_id | category_name
1 | category 1
2 | category 2
3 | category 3
product_categories:
pc_id | product_id | category_id
1 | 1 | 1
2 | 1 | 2
3 | 1 | 3
When I want to update product_categories
table, it doesn't update. I wanted to set just one category for my product and remove two others, but when I looked at my database I saw that it changed all the rows like:
product_categories:
pc_id | product_id | category_id
1 | 1 | 2
2 | 1 | 2
3 | 1 | 2
This is my code in view:
foreach($selected_categories as $selected_category){
$selected_category_options[] = $selected_category->category_Id;
}
echo form_multiselect('product_category_id[]', $category_options, set_value('product_category_id', $selected_category_options));
and this is the code in my Model:
foreach($_POST['product_category_id'] as $key => $product_category_id){
$options = array(
'category_Id' => $product_category_id
);
$this->db->where('product_id', $options['product_id']);
$this->db->update('product_categories', $options);
}
回答1:
First delete the categories and then insert
$options = array(
'category_Id' => $_POST['product_category_id'][0],
'product_id' => 'product id here'/* first category will be inserted only*/
);
$this->db->query("DELETE FROM product_categories WHERE product_id=". $options['product_id']); /* this will delete all categories assigned to $options['product_id']*/
$this->db->insert('product_categories', $options); /* will insert the first category from $_POST['product_category_id']*/
If you want a multi update then try this
$this->db->query("DELETE FROM product_categories WHERE product_id='product id here'";
foreach($_POST['product_category_id'] as $key => $product_category_id){
$options = array(
'category_Id' => $product_category_id,
'product_id' => 'product id here' /* first category will be inserted only*/
);
$this->db->insert('product_categories', $options);
}
来源:https://stackoverflow.com/questions/20291225/update-multiple-select-values-in-mysql-database-using-codeigniter