批量更新
UPDATE tiyan.dm_user_cupboard SET `res_id` = CASE `id` WHEN 1041 THEN '1' WHEN 1058 THEN '1' WHEN 1055 THEN '1' END,`food_code` = CASE `id` WHEN 1041 THEN '68' WHEN 1058 THEN '47' WHEN 1055 THEN '49' END,`food_name` = CASE `id` WHEN 1041 THEN '红枣' WHEN 1058 THEN '莲藕' WHEN 1055 THEN '洋葱' END,`num` = CASE `id` WHEN 1041 THEN '2' WHEN 1058 THEN '3' WHEN 1055 THEN '2' END,`level` = CASE `id` WHEN 1041 THEN '2' WHEN 1058 THEN '2' WHEN 1055 THEN '2' END,`update_time` = CASE `id` WHEN 1041 THEN '2017-12-09 21:40:06' WHEN 1058 THEN '2017-12-09 21:40:06' WHEN 1055 THEN '2017-12-09 21:40:06' END WHERE id IN ( 1041,1058,1055 ) |
附带基于tp的saveAll()
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
//批量更新public function saveAll($datas,$model){ ( $model || $model=$this->tableName); $model=empty($model)?$this->name:$model; $sql = ''; //Sql $lists = []; //记录集$lists $pk = $this->getPk();//获取主键 foreach ($datas as $data) { foreach ($data as $key=>$value) { if($pk===$key){ $ids[]=$value; }else{ $lists[$key].= sprintf("WHEN %u THEN '%s' ",$data[$pk],$value); } } } foreach ($lists as $key => $value) { $sql.= sprintf("`%s` = CASE `%s` %s END,",$key,$pk,$value); } $sql = sprintf('UPDATE __%s__ SET %s WHERE %s IN ( %s )',strtoupper($model),rtrim($sql,','),$pk,implode(',',$ids)); return M()->execute($sql);} |

浙公网安备 33010602011771号