Laravel Eloquent 获取层级的条件

Laravel Eloquent condition to fetch hierarchy level

Laravel Eloquent 获取层级的条件。

我有一个名为 routes 的 table,它是 self-referencing

示例数据:

(PK)                    
Id  title       route_id
1   users       null
2   home        null
3   foo         1      
4   bar         3      
5   hoge        3     

我想要一个根据层次结构获取路由的函数

$this->routes->getByHierarchyLevel(1);
// results                    
Id  title       route_id
1   users       null
2   home        null


$this->routes->getByHierarchyLevel(2);
// results                    
Id  title       route_id
3   foo         1

$this->routes->getByHierarchyLevel(3);
// results                    
Id  title       route_id
4   bar         3      
5   hoge        3

是否可以使用单个链接查询 builder/eloquent 生成器?

我已经为这个函数创建了一个自定义函数,但它是一个循环查询,或者另一个解决方案是获取所有内容并进行过滤。

我建议在你的路由 table 中引入一个新列 level 并在插入时检测它们的嵌套级别并将其保存在你的 table 中,这样你可以轻松执行过滤器而无需任何额外开销,否则您将需要 complex/expensive 查询才能检测其级别并应用过滤器


id title route_id level
1 users null 1
2 home null 1
3 foo 1 2
4 bar 3 3
5 hoge 3 3