request->param(); $page = $params['page'] ?? 1; $limit = $params['limit'] ?? 15; $where = []; if (!empty($params['name'])) { $where[] = ['name', 'like', "%{$params['name']}%"]; } if (isset($params['status']) ) { $where[] = ['status', '=',$params['status']]; } $count = DepartmentModel::where($where)->count(); $list = DepartmentModel::where($where) ->order('parent_id','asc') ->order('weight','desc') ->limit($limit) ->page($page) ->select(); return $this->success([ 'list' => $list, 'count' => $count, ]); } //获取部门树形结构 public function tree() { $list = DepartmentModel::where('status', 1) ->order('parent_id', 'asc') ->order('weight', 'desc') ->select(); $list = linear_to_tree($list); return $this->success($list); } //新增或编辑部门 public function update() { try { $params = (new DepartmentValidate)->post()->goCheck('edit'); $id = $this->request->param('id',0); $name = $params['name']; $parent_id = $params['parent_id'] ?? 0; $weight = $params['weight'] ?? 1; $status = $params['status'] ?? 1; if ($id) { $department = DepartmentModel::where('id', $id)->find(); if (!$department) { return $this->error('部门不存在'); } } else { $department = new DepartmentModel(); } $department->name = $name; $department->parent_id = $parent_id; $department->weight = $weight; $department->status = $status; $department->remark = $params['remark'] ?? ''; $department->save(); } catch (\Exception $e) { return $this->error($e->getMessage()); } return $this->success($department); } //设置部门状态 public function setStatus() { $params = (new DepartmentValidate)->goCheck('id'); $id = $params['id']; $department = DepartmentModel::where('id', $id)->find(); if (!$department) { return $this->error('部门不存在'); } $department->status = $department->status == 0 ? 1 : 0; $department->save(); return $this->success($department); } public function delete() { try { $params = (new DepartmentValidate)->goCheck('id'); $id = $params['id']; $department = DepartmentModel::where('id', $id)->find(); if (!$department) { return $this->error('部门不存在'); } //查询所有下级部门 $list = DepartmentModel::order('parent_id', 'asc') ->order('weight', 'desc') ->select(); $tree = linear_to_tree($list, 'children', 'id', 'parent_id', $id); DB::startTrans(); //获取所有下级的ID $ids = $this->getChildrenIds($tree); $ids[] = $id; $exists = Admin::whereIn('department_id', $ids)->count(); if ($exists) { return $this->error('该部门下有用户,不能删除'); } DepartmentModel::whereIn('id', $ids)->delete(); $department->delete(); DB::commit(); } catch (\Exception $e) { DB::rollBack(); return $this->error($e->getMessage()); } return $this->success([], '删除成功'); } //获取所有下级的ID private function getChildrenIds($sub) { $ids = []; foreach ($sub as $key => $value) { $ids[] = $value['id']; if (!empty($value['children'])) { $ids = array_merge($ids, $this->getChildrenIds($value['children'])); } } return $ids; } }