getDepartments($request); } public function publicSearch(Request $request) { return $this->getDepartments($request); } protected function getDepartments(Request $request) { $sort = $request->input('sort', 'desc'); $pageSize = $request->get('page_size') ?? 10; $departments = Department::filter($request->all())->orderBy('created_at', $sort)->paginate($pageSize); $departmentTree = !empty(make_tree($departments->toArray()['data'])) ? make_tree($departments->toArray()['data']) : $departments->toArray()['data']; return [ 'data' => $departmentTree, 'total' => $departments->total(), ]; } public function store(CreateOrUpdateRequest $request) { $department=new Department(); $department->mergeFillable([ 'company_id' ]); $department->fill([ ...$request->all(), 'company_id' => Auth::user()->company_id, ]); $department->save(); return $this->created(); } public function show(string $id) { $department=Department::query()->findOrFail($id); return new DepartmentResource($department); } public function update(CreateOrUpdateRequest $request,string $id) { $department=Department::findOrFail($id); $department->fill($request->all()); $department->save(); return $this->noContent(); } public function destroy(string $id) { $department = Department::findOrFail($id); if(!empty($department->children()->first())){ throw new \Exception("Please remove the sub-level departments."); } $department->delete(); return $this->noContent(); } public function departmentUserIndex(){ //封装部门 $departments=Department::query()->get(['id','name','parent_id'])->each(function ($departments){ $departments->new_id='department'.$departments->id; $departments->new_parent_id='department'.$departments->parent_id; $departments->type='department'; })->toArray(); //封装用户 $users=User::query()->where('company_id',Auth::user()->company_id)->get(['id','name','department_id'])->each(function ($users){ $users->new_id='user'.$users->id; $users->new_parent_id='department'.$users->department_id; $users->type='user'; })->toArray(); $departmentTree=$this->makeUserTree(array_merge($departments, $users)); return $this->success([ 'data' => $departmentTree ]); } protected function makeUserTree(array $departmentUsers, $parentId = 'department0') { $tree = []; if (empty($departmentUsers)) { return $tree; } $newList = []; foreach ($departmentUsers as $k => $v) { $newList[$v['new_id']] = $v; } foreach ($newList as $value) { if ($parentId == $value['new_parent_id']) { $tree[] = &$newList[$value['new_id']]; }elseif (isset($newList[$value['new_parent_id']])) { $newList[$value['new_parent_id']]['children'][] = &$newList[$value['new_id']]; } } return $tree; } }