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

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

    I've created a package that uses common table expressions (CTE) to implement recursive relationships: https://github.com/staudenmeir/laravel-adjacency-list

    You can use the ancestors relationship to get all parents of a model recursively:

    class YourModel extends Model
    {
        use \Staudenmeir\LaravelAdjacencyList\Eloquent\HasRecursiveRelationships;
    }
    
    $allParents = YourModel::find($id)->ancestors;
    

提交回复
热议问题