熟悉laravel的童鞋都知道,laravel有批量一次性插入多条记录,却没有一次性按条件更新多条记录。
是否羡慕thinkphp的saveAll,是否羡慕ci的update_batch,但如此优雅的laravel怎么就没有类似的批量更新的方法呢?
getTable(); // 表名
$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;
}
}
}
可以根据自己的需求再做调整,下面是用法实例:
// 要批量更新的数组
$students = [
['id' => 1, 'name' => '张三', 'email' => 'zhansan@qq.com'],
['id' => 2, 'name' => '李四', 'email' => 'lisi@qq.com'],
];
// 批量更新
app(Students::class)->updateBatch($students);
生成的SQL语句如下:
UPDATE pre_students
SET NAME = CASE
WHEN id = 1 THEN
'张三'
WHEN id = 2 THEN
'李四'
ELSE
NAME
END,
email = CASE
WHEN id = 1 THEN
'zhansan@qq.com'
WHEN id = 2 THEN
'lisi@qq.com'
ELSE
email
END
WHERE
id IN (1, 2)
---------------------
原文:https://blog.csdn.net/byywcsnd/article/details/78231429