【问题标题】:Codeigniter Active Record multi-updateCodeigniter Active Record 多次更新
【发布时间】:2013-08-01 14:25:04
【问题描述】:

如何使用活动记录更新多行?

我的数组

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

当我更新表格时,我需要在WHERE 子句中定义2 个参数(id_customer AND id_section),但如果我使用update_batch,我只能指定一个参数。 如何在WHERE子句中设置几个参数?

【问题讨论】:

标签: php codeigniter activerecord


【解决方案1】:

来自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'); 

在您的情况下,数据将替换为 $this->service_batch,标题将替换为您想要的列。

【讨论】:

  • 如果他需要 $data 数组中的 2 个 where 参数怎么办?这仅适用于给定的 id ?
  • @lxark 只需添加另一个 $this->db->where($this->db->where('id', $id); 语句 ...
  • 这不是我的意思...以您的方式,这仅适用于仅匹配一个ID。如果我需要匹配 $data 数组中每个数组的标题和 id 怎么办?你的意思是我真的需要为每个人添加一个 where 语句??
  • 似乎你想激怒我,我已经给出了答案的文档链接。无论如何你可以将关联数组传递给where(),如$array = array('name' => $name, 'title' => $title, 'status' => $status); $this->db->where($array);
【解决方案2】:

不太确定你到底需要什么,但我会这样做:

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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    • 2012-11-29
    • 2015-09-17
    • 1970-01-01
    相关资源
    最近更新 更多