88 lines
2.6 KiB
PHP
88 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace App\Models\Base;
|
|
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
class BaseModel extends Model
|
|
{
|
|
public $timestamps = false;
|
|
|
|
const LOCK_TYPE_FOR_UPDATE = 1;
|
|
const LOCK_TYPE_FOR_SHARE = 2;
|
|
const LOCK_TYPE = [
|
|
self::LOCK_TYPE_FOR_UPDATE => '悲观锁',
|
|
self::LOCK_TYPE_FOR_SHARE => '乐观锁',
|
|
];
|
|
|
|
function checkColInFill($aItem)
|
|
{
|
|
foreach ($aItem as $key => $value) {
|
|
if (!in_array($key, $this->fillable)) {
|
|
unset($aItem[$key]);
|
|
}
|
|
}
|
|
return $aItem;
|
|
}
|
|
|
|
function addItem($aItem): Model|\Illuminate\Database\Eloquent\Builder|bool
|
|
{
|
|
$aItem = $this->checkColInFill($aItem);
|
|
if (empty($aItem)) return false;
|
|
return $this->newQuery()->create($aItem);
|
|
}
|
|
|
|
function addItemWithCreateTime($aItem,$col = 'created_at'): Model|\Illuminate\Database\Eloquent\Builder|bool
|
|
{
|
|
$aItem = $this->checkColInFill($aItem);
|
|
if (empty($aItem)) return false;
|
|
$aItem[$col] = date('Y-m-d H:i:s');
|
|
return $this->newQuery()->create($aItem);
|
|
}
|
|
|
|
function delItem($id)
|
|
{
|
|
return $this->newQuery()->where($this->primaryKey, $id)->delete();
|
|
}
|
|
|
|
function updateItem($aItem,$col = null): bool|int
|
|
{
|
|
if(!$col) $col = $this->primaryKey;
|
|
$aItem = $this->checkColInFill($aItem);
|
|
if (empty($aItem)) return false;
|
|
if (!isset($aItem[$col])) return false;
|
|
if (empty($aItem[$col])) return false;
|
|
return $this->newQuery()->where($col,$aItem[$col])->update($aItem);
|
|
}
|
|
|
|
|
|
function findItem($id,$col=['*']): Model|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Builder|array|null
|
|
{
|
|
return $this->newQuery()->find($id,$col);
|
|
}
|
|
|
|
function findItemByWhere($aWhere,$col=['*']): Model|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Builder|array|null
|
|
{
|
|
return $this->newQuery()->where($aWhere)->first($col);
|
|
}
|
|
|
|
function getItemsByWhere($aWhere,$col=['*']): \Illuminate\Database\Eloquent\Collection|array
|
|
{
|
|
return $this->newQuery()->where($aWhere)->get($col);
|
|
}
|
|
|
|
function setLockByPrimaryKey($id,$lock_type = self::LOCK_TYPE_FOR_UPDATE): Model|\Illuminate\Database\Eloquent\Builder|null
|
|
{
|
|
$model = $this->newQuery()->where($this->primaryKey, $id);
|
|
if($lock_type == self::LOCK_TYPE_FOR_SHARE){
|
|
$model = $model->sharedLock();
|
|
}elseif ($lock_type == self::LOCK_TYPE_FOR_UPDATE){
|
|
$model = $model->lockForUpdate();
|
|
}
|
|
return $model->first();
|
|
}
|
|
|
|
|
|
|
|
}
|