如图我想实现点击左边的部门节点,右边加载该部门的所有员工,包括子部门的所有员工。如上图,点击人事行政部可以显示该部门人员,但是点击上级部门,就无法显示该部门下属部门的所有员工。求算法!
1 回答
幕布斯7119047
TA贡献1794条经验 获得超8个赞
我自己用递归方法已经实现了:
public function getUsersTables($department) { if($department == 1){ $users = User::all(); $users->map(function ($item, $key){ if ($item->status == 1){ return $item->status = '正常'; }else{ return $item->status = '禁用'; } }); $users->map(function ($item, $key){ if ($item->confirmed == 1){ return $item->confirmed = '已激活'; }else{ return $item->confirmed = '未激活'; } }); return Datatables::of($users)->make(true); }else{ //获取当前部门的所有员工对象 $before = User::where('department_id', $department)->get(); foreach ($before as $item){ array_push($this->child_users, $item); } //调用递归方法获取当前部门所有下属部门的ID,并循环获取所有部门ID的员工对象 foreach ($this->getChildDepartment($department) as $department_id){ $users = User::where('department_id', $department_id)->get(); foreach ($users as $user){ array_push($this->child_users, $user); } } $temp = collect($this->child_users); if (isset($temp)){ $temp->map(function ($item, $key){ if ($item->status == 1){ return $item->status = '正常'; }else{ return $item->status = '禁用'; } }); $temp->map(function ($item, $key){ if ($item->confirmed ==1){ return $item->confirmed = '已激活'; }else{ return $item->confirmed = '未激活'; } }); return Datatables::of($temp)->make(true); } } } /** * 递归方式获取当前被选部门下所有子部门ID * @param $parent_id * @return array */ public function getChildDepartment($parent_id) { //获取该部门ID所有下属部门ID $child_id = DB::table('departments')->select('id')->where('parent_id', $parent_id)->get(); $temp = collect($child_id); //如果集合为空,则返回子部门数组,否则继续获取当前部门集合中下属部门ID if ($temp->isEmpty()){ return $this->departments; }else{ foreach ($child_id as $id){ array_push($this->departments, $id->id); $this->getChildDepartment($id->id); } } return $this->departments; }
性能方面可能还有很多需要调优的地方,等有空再弄吧……
添加回答
举报
0/150
提交
取消