CI活动记录更新和update_batch之间的差异


difference between CI active record update and update_batch

我的应用程序使用CI。我现在想知道update()和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('id', 1)->update('user', $data);

用于update_batch();

 $data = array(
  array(
      'id'   => 1,
      'title' => 'My title' ,
      'name' => 'My Name 2' ,
      'date' => 'My date 2'
   ),
   array(
      'id'   => 1,
      'title' => 'Another title' ,
      'name' => 'Another Name 2' ,
      'date' => 'Another date 2'
   )
 );
 $this->db->update_batch('user', $data, 'id');

是的,有一个区别:连接到数据库的次数,在更新大量行时,这可能会极大地影响您的性能。在批量执行多个更新时,您只需连接一次数据库并更新所有行,否则,每次更新只连接一次,该时间将添加到执行时间中,从而损害性能。为了给你一个改进的想法,无批量与批量的对比是3分钟对7秒,有一次我不得不在一个小服务器中更新15000行。

关于你向我们展示的数据批次,你做得不对:这个想法是更新两个不同的行,所以如果你更新它们,id(你用来检查以选择行的字段)必须不同,否则你更新一行,然后再次更新同一行。检查以下差异:

 $data = array(
  array(
      'id'   => 1,
      'title' => 'My title' ,
      'name' => 'My Name 2' ,
      'date' => 'My date 2'
   ),
   array(
      // This id MUST BE of a different row if you want to achieve something, XD
      'id'   => 2,
      'title' => 'Another title' ,
      'name' => 'Another Name 2' ,
      'date' => 'Another date 2'
   )
 );
 $this->db->update_batch('user', $data, 'id');