封装优化
This commit is contained in:
101
extend/Aether/PHP/Hyperf/AbstractModel.php
Normal file
101
extend/Aether/PHP/Hyperf/AbstractModel.php
Normal 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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user