熟悉laravel的童鞋都知道,laravel有批量一次性插入多条记录,却没有一次性按条件更新多条记录。
可以将该方法封装到一个 BaseModel
里面
/**
* 批量更新
* @param array $multipleData 更新的数据
* @param string $key 更新的条件
* @return bool
* User: lizd
* Time: 2018/9/11 下午12:03
*/
public function updateBatch($multipleData = [],$key='id')
{
try {
if (empty($multipleData)) {
throw new \Exception("数据不能为空");
}
$tableName = $this->table; // 表名
$firstRow = current($multipleData);
if ( isset($firstRow[$key]) ) {
$referenceColumn = $key;
unset($firstRow[$key]);
$updateColumn = array_keys($firstRow);
} else {
throw new \Exception('索引条件不存在: the key is not existent!');
}
// 拼接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;
}
}
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 lzdong@foxmail.com