Overview
Rest Generic Class provides built-in support for hierarchical (tree) data structures. This is useful for:- Categories with parent-child relationships
- Organizational charts with employee hierarchies
- Menu systems with nested items
- Comment threads with replies
- File/folder structures with nested directories
Enabling Hierarchy Support
Define the Hierarchy Field
Add theHIERARCHY_FIELD_ID constant to your model:
The field name can be anything (
parent_id, parent_category_id, etc.) — just set HIERARCHY_FIELD_ID to match your database column.Automatic Helper Relations
WhenHIERARCHY_FIELD_ID is defined, BaseModel automatically provides:
RELATIONS constant to allow eager-loading:
Querying Hierarchical Data
List with Hierarchy
Use thehierarchy parameter to get nested tree structure:
Filter by Parent
Get children of a specific parent:Eager-Load Parent/Children
Tree Building
Automatic Tree Assembly
Whenhierarchy=true, the service automatically:
- Loads all records matching filters
- Organizes them into parent-child structure
- Returns only root-level nodes with nested children
Manual Tree Building
Build a tree from a flat collection:Common Patterns
Breadcrumb Trail
Get all ancestors of a node:Subtree Selection
Get all descendants of a node:Level/Depth Calculation
Compute depth of each node:Prevent Circular References
Validate parent assignment:Advanced Queries
Query with Depth Limit
Limit tree depth:Sorting Within Hierarchy
Add anorder field for custom sorting:
Database Optimization
Indexes
Add indexes for performance:Materialized Path (Alternative)
For very large trees, consider using a materialized path:Nested Set Model (Alternative)
For read-heavy hierarchies, use nested sets:Common Use Cases
Menu System
Organizational Chart
Comment Threading
Performance Considerations
- Eager-load relationships: Use
relationsparameter to avoid N+1 - Limit depth: Deep trees can be slow to build
- Cache trees: Store built trees in cache for read-heavy scenarios
- Pagination: Use pagination for large flat lists, hierarchy for tree views
- Database choice: Consider PostgreSQL’s recursive CTEs for complex queries
Error Handling
Related Documentation
- BaseModel Class - Model configuration
- Relation Loading - Loading parent/child relations
- Advanced Filtering - Filter by parent_id
- Hierarchical Data Guide - Detailed examples