我自己用遞歸方法已經(jīng)實現(xiàn)了:
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);
} //調(diào)用遞歸方法獲取當前部門所有下屬部門的ID,并循環(huán)獲取所有部門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); //如果集合為空,則返回子部門數(shù)組,否則繼續(xù)獲取當前部門集合中下屬部門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;
}
性能方面可能還有很多需要調(diào)優(yōu)的地方,等有空再弄吧……