Codeigniter Active Record multi-update

2019-08-28 20:17发布

问题:

How can I update multiple rows using active record?

My array

foreach($services as $service){

        $this->service_batch[]=array(
            'service_id'=>$service->service_id,
            'service_count'=>$service->service_count,
            'id_customer'=>$service->id_customer,
            'id_section'=>$service->id_section);
        }

When I update the table, I need define 2 parameters in the WHERE clause (id_customer AND id_section), but if I use update_batch, I can specify only one parameter. How can I set a few parameters in the WHERE clause?

回答1:

something like this from the Code Igniter Documentation - See Update Batch :-

 $data = array(
   array(
      'title' => 'My title' ,
      'name' => 'My Name 2' ,
      'date' => 'My date 2'
   ),
   array(
      'title' => 'Another title' ,
      'name' => 'Another Name 2' ,
      'date' => 'Another date 2'
   )
);

$this->db->where($this->db->where('id', $id);
$this->db->update_batch('mytable', $data, 'title'); 

in your case data will be replaced by $this->service_batch and title by your desired column.



回答2:

Not quite sure of catching what you exactly needs, but i would do:

//controller

foreach($services as $service){

        $this->model->update(
          $service->service_id,
          array(
            'service_count'=>$service->service_count,
            'id_customer'=>$service->id_customer,
            'id_section'=>$service->id_section
          ));
        }

//model


 function update($id,$data){

    $this->db->where('id',$id);
    return  $this->db->update('my_table',$data);

}