【发布时间】:2020-02-26 11:33:15
【问题描述】:
我有一个包含分支机构、部门和团队的表格。一个分支可以有很多部门,一个部门可以有很多团队。该类称为“组织”。
organisations 表:
id parent_id type name
1 null b Branch1
2 null b Branch2
3 1 d Dep1
4 2 d Dep2
5 3 t Team1
6 4 t Team2
我正在尝试在类中生成一个方法,该方法将递归返回树中给定位置的所有子记录。
我有一个叫children的关系:
/**
* Children
*/
public function children()
{
return $this->hasMany(Organisation::class, 'parent_id', 'id');
}
我在类中创建了一个名为tree的方法,如下:
/**
* Organisation Tree
*/
public function tree()
{
$merged = new Collection;
foreach($this->children as $child) {
$merged->merge($child->tree());
}
return $merged;
}
例如:
$o = Organisation::find(1);
$treeCollection = $o->tree();
$treeCollection 应该包含:
id parent_id type name
1 null b Branch1
3 1 d Dep1
4 3 t Team1
但是上面的方法返回并且清空集合并且它没有失败。我错过了什么?
【问题讨论】: