52 lines
2.1 KiB
PHP
52 lines
2.1 KiB
PHP
<?php
|
||
|
||
namespace App\Models;
|
||
|
||
use Illuminate\Database\Eloquent\Model;
|
||
use Illuminate\Support\Facades\DB;
|
||
|
||
/**
|
||
* @method static int update(array $values)
|
||
* @method static bool updateOrInsert(array $attributes, array $values = []) Insert or update a record matching the attributes, and fill it with values.
|
||
* @method static bool upsert(array $values, $uniqueBy, $update = null) insert new records or update the existing ones.
|
||
* @method static bool insert(array $values)
|
||
* @method static int insertOrIgnore(array $values)
|
||
* @method static int insertGetId(array $values, null|string $sequence)
|
||
* @method static int delete(mixed $id = null)
|
||
*/
|
||
class Base extends Model
|
||
{
|
||
public $timestamps = true;
|
||
|
||
public static function updateBatch($multipleData = []): int
|
||
{
|
||
$tableName = (new static())->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 = array_column($multipleData, $referenceColumn);
|
||
$bindings = array_merge($bindings, $whereIn);
|
||
$whereIn = rtrim(str_repeat('?,', count($whereIn)), ',');
|
||
$updateSql = rtrim($updateSql, ", ") . " WHERE `" . $referenceColumn . "` IN (" . $whereIn . ")";
|
||
// 传入预处理sql语句和对应绑定数据
|
||
return DB::update($updateSql, $bindings);
|
||
}
|
||
}
|