我可以将数组添加到 codeigniter 中 update_batch 的 where 子句中吗

2023-11-26

我正在使用代码点火器update_batch功能。

我想将一个数组作为第三个参数(where 子句)传递给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->update_batch('mytable', $data, 'title'); 

我想做这个:

 $this->db->update_batch('mytable', $data, array('title','name')); 

所以添加了多个where条件。

这可能吗?


您可以通过在模型 Test_model 中创建批量更新方法来完成此操作,例如,因为 Codeigniter 不支持本机 update_batch 中的多个 where 条件,因此示例如下:

public function update_batch_custom($table_name, $data, $indexes) {
    if (empty($data) || empty($indexes)){
        return 'Data or indexes must not be empty';
    }

    $db = $this->load->database('test_db', TRUE);
    $sql = 'UPDATE ' . $table_name . ' SET ' . "\n";

    //columns on which is done actual update
    $columns = [];
    foreach ($data[0] as $key => $value) {
        if (!in_array($key, $indexes)){
            $columns[] = $key;
        }
    }

    /*
     * forming WHEN .. THEN sql parts and WHERE condition
     */
    $parts = [];
    $where = [];
    foreach ($data as $row) {
        foreach ($columns as $column) {
            $sql_part = ' WHEN (';
            foreach ($indexes as $index) {
                 $sql_part .=  $index . '= \''.$row[$index] . '\' AND ';
                 $where[$index][] = $row[$index];
            }

            $sql_part = substr($sql_part, 0, -4);
            $sql_part .= ') THEN \'' . $row[$column] . '\'';
            $parts[$column][] = $sql_part;
        }
    }

    /*
     * connecting WHEN .. THEN parts for each column to be updated
     */
    foreach ($columns as $column) {
        $sql .= $column .'= CASE ';
        foreach ($parts[$column] as  $sql_part) {
            $sql .= $sql_part;
        }
        $sql .= ' ELSE ' . $column . ' END,';
    }

    /*
     * adding WHERE part
     */
    $sql = substr($sql, 0, -1);
    $sql .= ' WHERE ';
    foreach ($indexes as $index) {
        if ( count($where[$index]) > 0){
            $unique_where = array_unique($where[$index]);
            $sql .= $index . ' IN (\'' . join('\',\'', $unique_where) . '\') AND ';
        }
    }

    $sql = substr($sql, 0, -4);
    $sql .= ';';

    return $db->query($sql);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我可以将数组添加到 codeigniter 中 update_batch 的 where 子句中吗 的相关文章

随机推荐