Paolo Vincent
Paolo Vincent

Reputation: 387

Laravel Eloquent condition to fetch hierarchy level

Laravel Eloquent condition to fetch hierarchy level.

I have a table named routes and it is self-referencing

Sample data:

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

I would want to have a function to get routes according to its hierarchy

$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

Is there a single chained query builder/eloquent builder possible for this one?

I already made a custom function of this one but it is a looped query or the other solution is fetch all and filter.

Upvotes: 1

Views: 203

Answers (1)

M Khalid Junaid
M Khalid Junaid

Reputation: 64476

I would suggest to introduce a new column level in your routes table and at the time of insertion detect their nested level and save it in your table, this way you can perform your filters easily without any extra overhead , otherwise you would need complex/expensive queries to be able to detect their level and apply filter


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

Upvotes: 1

Related Questions