/**
* @param $table 表名
* @param array $multipleData 拼接的批量更新的数组格式:
* $students = [[‘id’ => 1, ‘city_id’ => ‘100010’],[‘id’ => 2, ‘city_id’ => ‘100011’],];
*拼接后语句:UPDATE base_info SET `city_id` = CASE WHEN `id` = 1 THEN 100010 WHEN `id` = 2 THEN 100011 ELSE `city_id` END WHERE `id` IN (1,2)
* @return false|int
*/
function updateBatch($tableName,$multipleData = [])
{
try {
if (empty($multipleData)) {
info("批量更新数据为空");
return false;
}
$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 . ")";
info($updateSql);
// 传入预处理sql语句和对应绑定数据
return DB::update($updateSql, $bindings);
} catch (\Exception $e) {
info($e->getMessage());
return false;
}
}
php批量更新多条数据
发布时间 2023-04-27 10:52:05作者: 成文的博客