2

我想用 codeignitersupdate_batch()函数更新数据库中的多行。
但是where 中指定的字段也应该更改。

以下代码应该清楚:

$set = array(
  array(
    'token'           => '65787131678754',
    'device'          => 'none',
    'new_token_value' => ''
  ),
  array(
    'token'           => '75798451315464',
    'device'          => 'none',
    'new_token_value' => ''
  )
);

$this->db->update_batch(TBL_NAME, $set, 'token');

中指定的标记token应使用deviceto更新,'none'并且其token本身应设置为空字符串''

这可能与update_batch()功能吗?


在 sql 我会写类似

UPDATE TBL_NAME
SET token='', device='none'
WHERE token='65787131678754'

一次更新,但这对于多次更新是不可行的,所以我想使用该update_batch()功能。

4

2 回答 2

0

我创建了一个与 codeigniter 函数基本相同的辅助batch_update()函数。
但具有更新索引本身的能力。新值由 定义index_update_key

function update_batch($db, $table = '', $set = NULL, $index = NULL, $index_update_key = '') {
if ($table === '' || is_null($set) || is_null($index) || !is_array($set)) {
    return FALSE;
}

$sql = 'UPDATE ' . $db->protect_identifiers($table) . ' SET ';

$ids = $when = array();
$cases = '';

//generate the WHEN statements from the set array
foreach ($set as $key => $val) {
    $ids[] = $val[$index];

    foreach (array_keys($val) as $field) {
        if ($field != $index && $field != $index_update_key) {
            $when[$field][] = 'WHEN ' . $db->protect_identifiers($index) 
                            . ' = ' . $db->escape($val[$index]) . ' THEN ' . $db->escape($val[$field]);
        } elseif ($field == $index) {
            //if index should also be updated use the new value specified by index_update_key
            $when[$field][] = 'WHEN ' . $db->protect_identifiers($index) 
                            . ' = ' . $db->escape($val[$index]) . ' THEN ' . $db->escape($val[$index_update_key]);
        }
    }
}

//generate the case statements with the keys and values from the when array
foreach ($when as $k => $v) {
    $cases .= "\n" . $db->protect_identifiers($k) . ' = CASE ' . "\n";
    foreach ($v as $row) {
        $cases .= $row . "\n";
    }

    $cases .= 'ELSE ' . $k . ' END, ';
 }

 $sql .= substr($cases, 0, -2) . "\n"; //remove the comma of the last case
 $sql .= ' WHERE ' . $index . ' IN (' . implode(',', $ids) . ')';

 return $db->query($sql);
}

现在我可以执行以下操作

$set = array(
  array(
    'token'           => '657871316787544',
    'device'          => 'none',
    'new_token_value' => ''
  ),
  array(
    'token'           => '757984513154644',
    'device'          => 'none',
    'new_token_value' => ''
  )
);

update_batch($this->db, 'table_name', $set, 'token', 'new_token_value');

并且sql输出是

UPDATE `b2c` SET 
`token` = CASE 
WHEN `token` = '657871316787544' THEN ''
WHEN `token` = '757984513154644' THEN ''
ELSE token END, 
`device` = CASE 
WHEN `token` = '657871316787544' THEN 'none'
WHEN `token` = '757984513154644' THEN 'none'
ELSE device END
WHERE token IN (657871316787544,757984513154644)
于 2013-06-05T11:06:44.160 回答
0
$this->db->where('option1', $option1);<br/>
$this->db->update_batch('table_name', $data, 'option2');
于 2014-08-29T05:57:51.047 回答