方法:
默认用$multipleData
数组中的第一个key作为主键更新
public function updateBatch($tableName,$multipleData = [])
{
try {
if (empty($multipleData)) {
throw new \Exception("数据不能为空");
}
$firstRow = current($multipleData);
$updateColumn = array_keys($firstRow);
// 默认以id为条件更新,如果没有ID则以第一个字段为条件
$referenceColumn = isset($firstRow['id']) ? 'id' : current($updateColumn);
unset($updateColumn[0]);
// 拼接sql语句
$updateSql = "UPDATE " . $tableName . " SET ";
$sets = [];
$bindings = [];
foreach ($updateColumn as $uColumn) {
$setSql = "`" . $uColumn . "` = CASE ";
foreach ($multipleData as $data) {
$setSql .= "WHEN `" . $referenceColumn . "` = ? THEN ? ";
$bindings[] = $data[$referenceColumn];
$bindings[] = $data[$uColumn];
}
$setSql .= "ELSE `" . $uColumn . "` END ";
$sets[] = $setSql;
}
$updateSql .= implode(', ', $sets);
$whereIn = collect($multipleData)->pluck($referenceColumn)->values()->all();
$bindings = array_merge($bindings, $whereIn);
$whereIn = rtrim(str_repeat('?,', count($whereIn)), ',');
$updateSql = rtrim($updateSql, ", ") . " WHERE `" . $referenceColumn . "` IN (" . $whereIn . ")";
// 传入预处理sql语句和对应绑定数据
return DB::update($updateSql, $bindings);
} catch (\Exception $e) {
return false;
}
}
更新示例:
使用数组中的key = id
作为主键更新,可根据业务需求变换
$update = array(
array('id'=>1,'name'=>'aa','area'=>'bb'),
array('id'=>2,'name'=>'cc','area'=>'dd'),
array('id'=>3,'name'=>'ee','area'=>'ff')
);
try{
$this->updateBatch($this->Create->getTable(),$update);
echo 'update success';
}catch (\Exception $e){
echo $e->getMessage();
}
网友评论