使用codeigniter在mysql数据库中更新多个选择值

问题描述:

我有多个选择我的产品类别,我有3个表为他们。我的表格如下:

I've got a multiple select for my product categories and I have 3 tables for them. My tables look like:

产品

product_id   |   product_name
     1       |    my_package

类别

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

当我要更新 product_categories ,它不更新。我想为我的产品设置一个类别,并删除两个其他,但当我看着我的数据库,我看到它改变了所有的行,如:

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

这是我的代码:

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);
}


先删除类别,然后插入

$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']*/

多更新,然后尝试此

$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);
}