CI批量更新$this->db->update_batch();

$this->db->update_batch();

生成一条update命令是以你提供的数据为基础的,并执行查询。你可以传递一个数组或对象的参数给update_batch()函数。下面是一个使用一个数组作为参数的示例:Generates an update string based on the data you supply, and runs the query. You can either pass an array or an object to the function. Here is an example using an array:

 1 $data = array(
 2    array(
 3       ‘title‘ => ‘My title‘ ,
 4       ‘name‘ => ‘My Name 2‘ ,
 5       ‘date‘ => ‘My date 2‘
 6    ),
 7    array(
 8       ‘title‘ => ‘Another title‘ ,
 9       ‘name‘ => ‘Another Name 2‘ ,
10       ‘date‘ => ‘Another date 2‘
11    )
12 );
13 
14 $this->db->update_batch(‘mytable‘, $data, ‘title‘); 
15 
16 // Produces: 
17 // UPDATE `mytable` SET `name` = CASE
18 // WHEN `title` = ‘My title‘ THEN ‘My Name 2‘
19 // WHEN `title` = ‘Another title‘ THEN ‘Another Name 2‘
20 // ELSE `name` END,
21 // `date` = CASE 
22 // WHEN `title` = ‘My title‘ THEN ‘My date 2‘
23 // WHEN `title` = ‘Another title‘ THEN ‘Another date 2‘
24 // ELSE `date` END
25 // WHERE `title` IN (‘My title‘,‘Another title‘)

参数1:表名 参数2:如上所示的二维数组 参数3:键名.


提示: 所有的值都会自动进行安全性过滤.

 

即:

UPDATE `mytable`
SET `name` = CASE
WHEN `title` = ‘My title‘ THEN
‘My Name 2‘
WHEN `title` = ‘Another title‘ THEN
‘Another Name 2‘
ELSE
`name`
END,
`date` = CASE
WHEN `title` = ‘My title‘ THEN
‘My date 2‘
WHEN `title` = ‘Another title‘ THEN
‘Another date 2‘
ELSE
`date`
END
WHERE
`title` IN (‘My title‘, ‘Another title‘)

-----------------------------------------------------------

比如要批量更新状态未读为已读:

$data = array(
array(
‘id‘ => ‘1‘ ,
‘status‘ => ‘READ‘

),
array(
‘id‘ => ‘2‘ ,
‘status‘ => ‘READ‘
)
);

$this->db->update_batch(‘mytable‘, $data, ‘id‘);

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。