query()->orderByDesc('sort')->get()->toArray(); return array2tree($list); } public function getModelFilter() { return $this->modelFilterName; } public function listQuery() { $model = $this->getModel(); $filter = $this->getModelFilter(); $query = $this->query(); if ($this->withRelationships) { $query->with($this->withRelationships); } if ($filter) { $query->filter(request()->input(), $filter); } return $query->orderByDesc($model->getKeyName()); } public function list() { $query = $this->listQuery(); $list = (clone $query)->paginate(request()->input('perPage', 20)); $items = $list->items(); $total = $list->total(); return compact('items', 'total'); } public function getDetail($id) { return $this->query()->with($this->withRelationships)->find($id); } public function store($data): bool { $data = $this->resloveData($data); $validate = $this->validate($data); if ($validate !== true) { $this->setError($validate); return false; } $model = $this->modelName::create($data); $this->afterCreate($model); return true; } public function update($primaryKey, $data): bool { $model = $this->query()->whereKey($primaryKey)->firstOrFail(); $data = $this->resloveData($data, $model); $validate = $this->validate($data, $model); if ($validate !== true) { $this->setError($validate); return false; } return $model->update($data); } public function delete(string $ids): mixed { $id = explode(',', $ids); $result = $this->preDelete($id); if ($result !== true) { $this->setError($result); return false; } return $this->query()->whereIn($this->primaryKey(), $id)->delete(); } /** * 处理表单数据 * * @param array $data * @param mixed $model * @return array */ public function resloveData($data, $model = null) { return $data; } /** * 表单验证 * * @param array $data * @param mixed $model 空: 添加, 非空: 当前数据模型 * @return mixed true: 验证通过, string: 错误提示 */ public function validate($data, $model = null) { return true; } /** * 删除的前置方法 * * @param array $ids 主键id * @return mixed true: 继续后续操作, string: 中断操作, 返回错误提示 */ public function preDelete(array $ids) { return true; } /** * 数据创建成功 * * @param $model * @return void */ public function afterCreate($model) { } }