【问题标题】:batch update in codeigniter with simple array使用简单数组在 codeigniter 中批量更新
【发布时间】:2014-01-31 19:37:59
【问题描述】:

我想在 codeignter 中进行批量更新并传递数组数据,而不是运行多个查询。

Array ( [439] => 0 [440] => 0 [441] => 0 [442] => 1 [443] => 0 )

439、440、441、442、443 是 id,0、0、0、1、0 是需要放入活动列的值。

我可以通过循环运行它来实现这一点,但我想进行批量更新。

foreach($this->input->post($field_name) as $key => $value)
{
    $insert = array(
        'id'        =>  $key,
        'active'    =>  $value,
    );

    $this->db->where('id', $key)->update($table, array('active' => $value));
}   

【问题讨论】:

  • 任何答案对你有用吗?
  • 有趣。当您在视图上启用输出分析器时,数据库查询会发生什么?

标签: php arrays codeigniter activerecord


【解决方案1】:

使用 foreach 循环构建数组,然后使用批量更新。

编辑:我忘记了开头数组中的第二个array()。它可能需要也可能不需要。

$data = array(array());

foreach($this->input->post($field_name) as $key => $value)
{
    $push = array(
        'id'        =>  $key,
        'active'    =>  $value,
    );
array_push($data, $push);
}
$this->db->update_batch('mytable', $data, 'id');

【讨论】:

    【解决方案2】:

    遍历您的数组并使用关联数组来存储数据

    foreach($this->input->post($field_name) as $key => $value)
    {
      $insert[] = array(
         'id'        =>  $key,
         'active'    =>  $value
      );
    
    }   
    $this->db->update_batch('yourtable', $insert, 'id');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-23
      • 1970-01-01
      • 2011-09-10
      • 1970-01-01
      相关资源
      最近更新 更多