【问题标题】:Laravel 5.8 create a recursive collectionLaravel 5.8 创建递归集合
【发布时间】: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

但是上面的方法返回并且清空集合并且它没有失败。我错过了什么?

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    这是我的解决方案:

    /**
     * Organisation Tree
     */
    public function tree()
    {
        $merged = new Collection;
    
        $merged = $merged->merge($this->children);
    
        foreach($this->children as $child) {
            $merged = $merged->merge($child->tree());
        }
    
        return $merged;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-03
      • 2019-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多