模型优化

This commit is contained in:
Aether
2025-09-28 16:15:46 +08:00
parent 7bccb0e9fe
commit 1fc9d85ff0
2 changed files with 3 additions and 211 deletions

View File

@@ -59,7 +59,6 @@ class Campus extends AetherModel
/**
* 获取父级校区.
* @return BelongsTo
*/
public function parent(): BelongsTo
{
@@ -110,7 +109,6 @@ class Campus extends AetherModel
/**
* 获取校区下的老师.
* @return HasMany
*/
public function teachers(): HasMany
{
@@ -118,5 +116,4 @@ class Campus extends AetherModel
->where('status', 1)
->whereNull('deleted_at');
}
}

View File

@@ -9,7 +9,6 @@ use Closure;
use DateTime;
use Exception;
use Hyperf\Context\ApplicationContext;
use Hyperf\Contract\LengthAwarePaginatorInterface;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Collection;
use Hyperf\Database\Model\ModelNotFoundException;
@@ -92,60 +91,6 @@ abstract class AetherModel extends HyperfModel implements CacheableInterface
return null;
}
/**
* 列表查询.
*/
// public function list(array $params = []): array
// {
// $query = $this->newQuery();
//
// // 通过模型配置自动应用所有搜索条件
// $this->applySearch($query, $params);
//
// // 动态应用排序
// $sortConfig = $this->getSortConfig();
// if ($sortConfig) {
// $query->orderBy($sortConfig['field'], $sortConfig['direction']);
// }
//
// $withDeleted = filter_var($params['with_deleted'] ?? false, FILTER_VALIDATE_BOOLEAN);
// if ($withDeleted) {
// $query->withTrashed();
// }
//
// // 存在分页参数page或size则进行分页查询
// if (isset($params['page']) || isset($params['size'])) {
// $page = (int) ($params['page'] ?? 1);
// $size = (int) ($params['size'] ?? 10);
// $page = max(1, $page);
// $size = max(1, min(100, $size));
// $result = $query->paginate($size, ['*'], 'page', $page);
// return [
// 'total' => $result->total(),
// 'list' => $result->items(),
// ];
// }
//
// // 无分页参数时返回完整数据集合
// $items = $query->get()->toArray();
//
// // 若模型支持树形结构则构建树形,否则返回普通数组
// if ($this instanceof TreeableInterface) {
// return $this::buildTree($items, (int) ($params['parent_id'] ?? 0));
// }
//
// return $items;
// }
/**
* 列表查询.
*/
// public function list(array $params = []): array
// {
// $query = $this->buildQueryFromParams($params);
// return $this->listResult($query, $params);
// }
public function list(array $params = []): array
{
$query = static::query();
@@ -190,51 +135,6 @@ abstract class AetherModel extends HyperfModel implements CacheableInterface
return $items;
}
/**
* 根据模型的$search配置自动应用搜索条件到查询构建器.
*/
// public function applySearch(Builder $query, array $params): void
// {
// foreach ($this->search as $field => $rule) {
// // 跳过未传递的参数
// if (!isset($params[$field])) {
// continue;
// }
//
// $value = $params[$field];
// $this->applySearchRule($query, $field, $value, $rule);
// }
// }
//
// /**
// * 应用单个搜索规则
// */
// protected function applySearchRule(Builder $query, string $field, $value, $rule): void
// {
// // 处理规则格式(支持字符串简写或数组配置)
// $config = is_array($rule) ? $rule : ['type' => $rule];
// $type = $config['type'];
//
// switch ($type) {
// case '=': // 精确匹配
// $query->where($field, $value);
// break;
// case 'like': // 模糊匹配
// $query->where($field, 'like', "%{$value}%");
// break;
// case 'between': // 范围查询(支持数组或两个参数)
// $values = is_array($value) ? $value : [$value, $params[$field . '_end'] ?? $value];
// $query->whereBetween($field, $values);
// break;
// case 'callback': // 自定义回调
// if (isset($config['handler']) && is_callable($config['handler'])) {
// call_user_func($config['handler'], $query, $value);
// }
// break;
// // 可扩展其他类型in、>、< 等
// }
// }
/**
* 快捷创建.
*/
@@ -289,7 +189,6 @@ abstract class AetherModel extends HyperfModel implements CacheableInterface
* 快捷查找或失败.
* @param int $id 要查找的记录ID
* @return AetherModel 根据ID查找记录不存在则抛出异常
* 根据ID查找记录不存在则抛出异常
* @throws Exception 当删除操作发生其他错误时抛出
* @throws ModelNotFoundException 当记录不存在时抛出
*/
@@ -305,45 +204,6 @@ abstract class AetherModel extends HyperfModel implements CacheableInterface
return $record; // static::query()->findOrFail($id);
}
/**
* 获取列表.
*/
public static function getList(
array $conditions = [],
array $columns = ['*'],
array $orders = []
): Collection {
$query = static::buildQuery($conditions, $orders);
return $query->get($columns);
}
/**
* 分页查询列表.
*/
public static function getPageList(
array $conditions = [],
int $page = 1,
int $pageSize = 10,
array $columns = ['*'],
array $orderBy = []
): LengthAwarePaginatorInterface {
// 直接通过静态方法链构建查询
$query = static::query();
// 应用条件
foreach ($conditions as $field => $value) {
$query->where($field, $value);
}
// 应用排序
foreach ($orderBy as $field => $direction) {
$query->orderBy($field, $direction);
}
// 执行分页
return $query->paginate($pageSize, $columns, 'page', $page);
}
/**
* 获取器处理.
*/
@@ -382,52 +242,6 @@ abstract class AetherModel extends HyperfModel implements CacheableInterface
return Db::transaction($closure);
}
/**
* 应用排序.
*/
protected function applySorting(Builder $query, array $params = []): void
{
// 优先使用传入的排序参数
if (isset($params['sort_field'], $params['sort_direction'])) {
$query->orderBy($params['sort_field'], $params['sort_direction']);
return;
}
// 使用模型配置的排序
$sortConfig = $this->getSortConfig();
if (! empty($sortConfig)) {
$query->orderBy($sortConfig['field'], $sortConfig['direction']);
}
}
/**
* 根据分页参数获取结果.
*/
protected function listResult(Builder $query, array $params = []): array
{
// 分页处理
if (isset($params['page'], $params['size'])) {
$page = max(1, (int) $params['page']);
$size = max(1, min(100, (int) $params['size']));
$result = $query->paginate($size, ['*'], 'page', $page);
return [
'list' => $result->items(),
'total' => $result->total(),
];
}
// 获取所有数据
$result = $query->get()->toArray();
// 如果实现了树结构接口,构建树
if ($this instanceof TreeableInterface) {
return $this->buildTree($result, $params['parent_id'] ?? 0);
}
return $result;
}
/**
* 初始化模型.
*/
@@ -540,14 +354,14 @@ abstract class AetherModel extends HyperfModel implements CacheableInterface
};
}
// 数字格式化(示例参数化实现)
// 数字格式化
protected function formatNumber($value, array $params): string
{
$precision = $params['precision'] ?? 2; // 默认保留2位小数
return number_format((float) $value, $precision);
}
// 字符串截断(示例参数化实现)
// 字符串截断
protected function truncateString($value, array $params): string
{
$length = $params['length'] ?? 20; // 默认截断到20字符
@@ -560,32 +374,13 @@ abstract class AetherModel extends HyperfModel implements CacheableInterface
: $value;
}
// 枚举映射(示例参数化实现)
// 枚举映射
protected function mapEnum($value, array $params): mixed
{
$map = $params['map'] ?? []; // 枚举映射表,如 [1 => '男', 2 => '女']
return $map[$value] ?? $value;
}
// 修正 buildQuery 方法,避免使用 new static()
protected static function buildQuery(array $conditions = [], array $orderBy = []): Builder
{
// 使用静态 query() 方法获取查询构建器
$query = static::query();
// 处理搜索条件
foreach ($conditions as $field => $value) {
$query->where($field, $value);
}
// 处理排序
foreach ($orderBy as $field => $direction) {
$query->orderBy($field, $direction);
}
return $query;
}
/**
* 应用搜索条件.
*/