我有一个名为department
的表,该表本身具有父/子关系。一个部门可以没有孩子,也可以有很多孩子,我现在的问题是,我该如何在父母的表中按顺序显示其子女?例如:
Parent A
Child A
Child Y
Parent B
Parent C
Child F
Child N
我什至在sql中尝试过,但我没有运气:
select d.name from departments d left join departments dd on d.id = dd.parent_id ORDER by d.name
答案 0 :(得分:2)
Laravel可以很好地处理此问题(双关语)。只需定义一个模型和2个关系:
class Department extends Model(){
public function parent(){
return $this->belongsTo(self::class, "parent_id", "id");
}
public function children(){
return $this->hasMany(self::class, "parent_id", "id");
}
}
然后,在查询时,最初将目标对象定位为没有父级的人员(“顶级”部门)
$departments = Department::doesntHave("parent")->with(["children"])->get();
然后,只需循环$departments
及其"children"
:
foreach($departments AS $department){
echo $department->name;
foreach($department->children AS $child){
echo $child->name;
}
}
由于这些是嵌套循环,因此您将获得正确的结果;每个“顶级”部门都将立即列出,其子级成员后跟0到X。