封装优化

This commit is contained in:
阿不叮咚
2025-09-24 15:38:44 +08:00
parent c272fc80b8
commit edd4effc95
14 changed files with 493 additions and 21 deletions

View File

@@ -0,0 +1,101 @@
<?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(int $id, $columns = []): self
{
$model = self::find($id);
if (!$model) {
throw new ModelNotFoundException();
}
return $model;
}
/**
* 创建记录并返回实例
*/
public static function createOne(array $data): self
{
$model = new static();
$model->fill($data);
$model->save();
return $model;
}
/**
* 更新记录
*/
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();
}
}