需要将每个员工的部门的全路径循环输入。
当用户量起来的时候,如果使用无限极递归,就会出现超过最大层级256问题和内存溢出等问题。因此,就针对这个问题进行优化。
优化思想:
第一.避开循环内sql查询(IO开销)
第二.使用无限极递归放在内存和层级超限。
public function getEmployees($company_id){
//获取该公司下所有部门,并组装需要
$deptSql = " select id,parent_id,deptName from department where company_id = {$company_id} and status =1 ";
$deptInfo = DB::select($deptSql);
$allDep = [];
foreach ($deptInfo as &$value) {
$allDep[$value->id] = ['id'=>$value->id,'parent_id'=>$value->parent_id,'deptName'=>$value->deptName];
}
//获取所有员工
$sql = " select fullName,eid,deptid from employees where company_id = {$company_id} and del=0 and employees_status<3";
$employees = DB::select($sql);
foreach($employees as &$employee){
//获取部门全路径
if( $employee->deptid > 0 ){
$employee->dept_path = self::getFather($allDep,$employee->deptid);
}
}
return employees;
}
/**
* @param array $arr 部门数组
* @param integer $id 部门id 默认为顶级
* @param string $str 部门全路径 默认为空
* @return string
*/
public static function getFather($arr, $id=0, $str = '')
{
//预设计部门层级最大为10层,根据公司需要而定
for ($i=0; $i < 10; $i++) {
if( isset($arr[$id]) ){
$str .= $arr[$id]['deptName'].'-';
//非顶级且不是父级的
if( $arr[$id]['parent_id'] != 0 && $id != $arr[$id]['parent_id'] ){
$id = $arr[$id]['parent_id'];
}else{
break;
}
}
}
//反转排序
if(!empty($str)){
$str = rtrim($str,'-');
$str = explode('-',$str);
krsort($str);
$str = implode('-',$str);
}
return $str;
}