方法1:
$sql="UPDATE $this->table SET ";
$primarykeyfield="id";
$updatekeys=array_keys($data[0]);
$sql.=array_reduce($updatekeys,function($a,$b) use ($data,$primarykeyfield){
if($b != $primarykeyfield) {
$cache = $b . "= case " . $primarykeyfield . " ";
$v = array_reduce($data, function ($c, $d) use ($b, $primarykeyfield) {
return $c .= " when " . $d[$primarykeyfield] . " then " . $d[$b];
}, "");
if (!empty($v)) {
$a .= $cache . $v." end, ";
}
}
return $a;
}," ");
$sql=rtrim($sql, ', ');
$sql.=" where ".$primarykeyfield." IN (".implode(',',array_column($data,$primarykeyfield)).")";
只用什么一个data数组
[['aaa'=>1,'number'=>3,'id'=>2],['aaa'=>2,'number'=>12,'user_id'=>2]]
再修primarykeyfield="主键名称"
执行
Db::execute($sql);
方法2:
可以例如上面数组在模型里面只需要
$list = [
['aaa'=>1,'number'=>3,'id'=>2],
['aaa'=>2,'number'=>12,'user_id'=>2,'id'=>3]
];
$this->saveAll($list);
缺点有bug就是如果表没有主键的会报错
还有如果数组只有一条也会报错提交数据不存在:method not exist:think\db\Query->saveAll
我看了哈,有bug但是不想动底层,因为后期框架升级很麻烦,
方法3:
循环使用里面update来更新
$savenumber=0;
foreach($list as $key=>$val){
$id=$val['id']; unset($val['id']); $savenumber += $this->where(['id'=>$id])->update($val);
}