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

前端 未结 5 1891
生来不讨喜
生来不讨喜 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:34

    So after fiddling around with the merge() method for the Collections class:

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

    That will produce what I needed, however I believe it can be more cleaner so please feel free to edit it!

提交回复
热议问题