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

前端 未结 5 2017
生来不讨喜
生来不讨喜 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条回答
  •  Happy的楠姐
    2021-02-06 08:22

    I modified tiffanyhwang solution and turned it into a non-static method and included a attribute accessor to make it easier to get results.

    public function ancestors()
    {
        $ancestors = $this->where('id', '=', $this->parent_id)->get();
    
        while ($ancestors->last() && $ancestors->last()->parent_id !== null)
        {
            $parent = $this->where('id', '=', $ancestors->last()->parent_id)->get();
            $ancestors = $ancestors->merge($parent);
        }
    
        return $ancestors;
    }
    

    and accessor to retrieve a collection of ancestors from model attribute

    public function getAncestorsAttribute()
    {
        return $this->ancestors();
        // or like this, if you want it the other way around
        // return $this->ancestors()->reverse();
    }
    

    so now you can get ancestors like this:

    $ancestors = $model->ancestors;
    

    and since its a Collection, you can now easily do for example this:

    echo $model->ancestors->implode('title',', ');
    

提交回复
热议问题