query()->filter(request()->all(), $this->modelFilterName)->orderByDesc('sort')->get(); $minNum = $list->min('parent_id'); return array2tree($list->toArray(), $minNum); } public function parentIsChild($id, $pid): bool { $parent = $this->query()->find($pid); do { if ($parent->parent_id == $id) { return true; } // 如果没有parent 则为顶级 退出循环 $parent = $parent->parent; } while ($parent); return false; } public function list() { return ['items' => $this->getTree()]; } public function store($data): bool { if ($this->hasRepeated($data)) { return false; } $columns = $this->getTableColumns(); $model = $this->getModel(); foreach ($data as $k => $v) { if (!in_array($k, $columns)) { continue; } $model->setAttribute($k, $v); } return $model->save(); } public function update($primaryKey, $data): bool { if ($this->hasRepeated($data, $primaryKey)) { return false; } $columns = $this->getTableColumns(); $pid = Arr::get($data, 'parent_id'); if ($pid != 0) { if ($this->parentIsChild($primaryKey, $pid)) { $this->setError('父级不允许设置为当前子权限'); return false; } } $model = $this->query()->whereKey($primaryKey)->first(); foreach ($data as $k => $v) { if (!in_array($k, $columns)) { continue; } $model->setAttribute($k, $v); } return $model->save(); } public function hasRepeated($data, $id = 0): bool { $query = $this->query()->when($id, fn($query) => $query->where('id', '<>', $id)); if ((clone $query)->where('key', $data['key'])->exists()) { $this->setError('KEY重复'); return true; } return false; } public function delete(string $ids): mixed { $ids = explode(',', $ids); if(count($ids) == 1){ $this->query()->where('path', 'like', '%-'.$ids[0].'-%')->delete(); } return $this->query()->whereIn('id', $ids)->delete(); } }