query()->orderByDesc('sort')->get(); $minNum = $list->min('parent_id'); return array2tree($list->toArray(), $minNum); } 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); } if($this->modelSortAble){ $query->sort(); } $this->sortable($query); return $query; } 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; } $this->modelName::create($data); 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 Model $model 空 : 添加, 非空: 修改 * @return array */ public function resloveData($data, $model = null) { return $data; } /** * 表单验证 * * @param array $data * @param Model $model 空: 添加, 非空: 修改 * @return mixed true: 验证通过, string: 错误提示 */ public function validate($data, $model = null) { // $createRules = [ // 'key' => ['required', Rule::unique('keywords', 'key')], // 'name' => ['required'], // ]; // $updateRules = [ // 'key' => [Rule::unique('keywords', 'key')->ignore($model->id)] // ]; // $validator = Validator::make($data, $model ? $updateRules : $createRules, [ // 'key.unique' => ':input 已经存在' // ]); // if ($validator->fails()) { // return $validator->errors()->first(); // } return true; } /** * 删除的前置方法 * * @param array $ids 主键id * @return mixed true: 继续后续操作, string: 中断操作, 返回错误提示 */ public function preDelete(array $ids) { return true; } }