Laravel query builder for recursive results? E.g. id, parent_id

前端 未结 5 1905
生来不讨喜
生来不讨喜 2021-02-06 07:39

So I have data structured like this:

id|parent_id|name
1 |null     |foo
2 |1        |bar
3 |2        |baz

So basically foo->bar->ba

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-06 08:39

    I modified ruuter answer to use relationships. If you have a parent() belongsTo relationship on the model you can use that one to remove the where clause, see below:

    public function parents()
    {
            $parents = $this->parent()->get();
    
            while ($parents->last() && $parents->last()->parent_id !== null) {
                    $parent = $parents->last()->parent()->get();
                    $parents = $parents->merge($parent);
            }
    
            return $parents;
    }
    

    And then you can access it:

    public function allParents(): Collection 
    {
            return $this->parents();
    }
    

提交回复
热议问题