admin-api/app/common/model/BaseModel.php

104 lines
2.3 KiB
PHP
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace app\common\model;
use think\db\BaseQuery;
use think\facade\Db;
use think\Model;
/**
* Class BaseModel
* @package app\common\model
* @author xaboy
* @day 2020-03-30
*/
abstract class BaseModel extends Model
{
protected $updateTime = false;
/**
* @return string
* @author xaboy
* @day 2020-03-30
*/
abstract public static function tablePk():? string;
/**
* @return string
* @author xaboy
* @day 2020-03-30
*/
abstract public static function tableName(): string;
/**
* BaseModel constructor.
* @param array $data
*/
public function __construct(array $data = [])
{
$this->pk = static::tablePk();
$this->name = static::tableName();
parent::__construct($data);
}
/**
* @return static
*/
public static function getInstance(): self
{
return new static();
}
/**
* @param array $scope
* @return BaseQuery
* @author xaboy
* @day 2020-03-30
*/
public static function getDB(array $scope = [])
{
return self::getInstance()->db($scope);
}
public static function batchUpdate(array $update, $whenField = 'id', $whereField = 'id', $raw = false){
$when = [];
$ids = [];
foreach ($update as $sets) {
# 跳过没有更新主键的数据
if (!isset($sets[$whenField])) {
continue;
}
$whenValue = $sets[$whenField];
foreach ($sets as $fieldName => $value) {
#主键不需要被更新
if ($fieldName == $whenField) {
array_push($ids, $value);
continue;
};
if ($raw) {
$when[$fieldName][] = "when {$whenValue} then {$value}";
} else {
$when[$fieldName][] = "when '{$whenValue}' then '{$value}'";
}
}
}
# 没有更新的条件id
if (!$when) return false;
$query = self::whereIn($whereField, $ids);
# 组织sql
foreach ($when as $fieldName => &$item) {
$item = Db::raw("case $whenField " . implode(' ', $item) . ' end ');
}
return $query->update($when);
}
}