1

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.

2
  • 1
    It would be easier if you can record the level at the time of insertion in table and store that level that can save you from complex queries and overhead Commented Feb 23, 2021 at 16:58
  • Thanks, it is actually the best solution Commented Feb 24, 2021 at 1:54

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.