98 lines
1.9 KiB
PHP
98 lines
1.9 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Aether;
|
|
|
|
use Exception;
|
|
use Hyperf\Database\Model\Builder;
|
|
use Hyperf\Database\Model\ModelNotFoundException;
|
|
use Hyperf\Database\Model\SoftDeletes;
|
|
|
|
abstract class AbstractModel extends AetherModel
|
|
{
|
|
use SoftDeletes;
|
|
|
|
/**
|
|
* 时间戳字段格式
|
|
* @var string|null
|
|
*/
|
|
protected ?string $dateFormat = 'Y-m-d H:i:s';
|
|
|
|
/**
|
|
* 可批量赋值的字段
|
|
* @var array
|
|
*/
|
|
protected array $fillable = [];
|
|
|
|
/**
|
|
* 日期字段
|
|
* @var array
|
|
*/
|
|
protected array $dates = [
|
|
'created_at',
|
|
'updated_at',
|
|
'deleted_at',
|
|
];
|
|
|
|
/**
|
|
* 字段类型转换
|
|
* @var array
|
|
*/
|
|
protected array $casts = [
|
|
'id' => 'integer',
|
|
'created_at' => 'datetime',
|
|
'updated_at' => 'datetime',
|
|
'deleted_at' => 'datetime',
|
|
];
|
|
|
|
/**
|
|
* 启用状态查询作用域
|
|
*/
|
|
public function scopeEnabled(Builder $query): Builder
|
|
{
|
|
return $query->where('status', 1);
|
|
}
|
|
|
|
/**
|
|
* 按ID查询并检查存在性
|
|
* @param int $id
|
|
* @param array $columns
|
|
* @return AbstractModel
|
|
*/
|
|
public static function findOrFail(mixed $id, $columns = []): self
|
|
{
|
|
$model = self::find($id, $columns);
|
|
if (!$model) {
|
|
throw new ModelNotFoundException();
|
|
}
|
|
return $model;
|
|
}
|
|
|
|
/**
|
|
* 创建记录并返回实例
|
|
*/
|
|
public static function createOne(array $data): self
|
|
{
|
|
return static::query()->create($data);
|
|
}
|
|
|
|
/**
|
|
* 更新记录
|
|
*/
|
|
public static function updateById(int $id, array $data): bool
|
|
{
|
|
$model = self::findOrFail($id);
|
|
return $model->update($data);
|
|
}
|
|
|
|
/**
|
|
* 删除记录
|
|
* @throws Exception
|
|
*/
|
|
public static function deleteById(int $id): bool
|
|
{
|
|
$model = self::findOrFail($id);
|
|
return $model->delete();
|
|
}
|
|
} |