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');

 

posted @ 2015-03-05 11:58  谦信君  阅读(17488)  评论(0编辑  收藏  举报