goodsnotices/app/Models/Base.php

52 lines
2.1 KiB
PHP
Raw Normal View History

2024-05-25 14:06:58 +00:00
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
2024-05-26 14:06:21 +00:00
use Illuminate\Support\Facades\DB;
2024-05-25 14:06:58 +00:00
2024-05-26 14:06:21 +00:00
/**
* @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)
*/
2024-05-25 14:06:58 +00:00
class Base extends Model
{
public $timestamps = true;
2024-05-26 14:06:21 +00:00
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);
}
2024-05-25 14:06:58 +00:00
}