Skip to main content

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 the HIERARCHY_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

When HIERARCHY_FIELD_ID is defined, BaseModel automatically provides:
Add these to your RELATIONS constant to allow eager-loading:

Querying Hierarchical Data

List with Hierarchy

Use the hierarchy parameter to get nested tree structure:
Response:

Filter by Parent

Get children of a specific parent:
Get root-level items (no parent):

Eager-Load Parent/Children

Response:

Tree Building

Automatic Tree Assembly

When hierarchy=true, the service automatically:
  1. Loads all records matching filters
  2. Organizes them into parent-child structure
  3. Returns only root-level nodes with nested children

Manual Tree Building

Build a tree from a flat collection:

Common Patterns

Get all ancestors of a node:
Result:

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 an order field for custom sorting:
Request:

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

Build navigation:

Organizational Chart

Comment Threading

Performance Considerations

  1. Eager-load relationships: Use relations parameter to avoid N+1
  2. Limit depth: Deep trees can be slow to build
  3. Cache trees: Store built trees in cache for read-heavy scenarios
  4. Pagination: Use pagination for large flat lists, hierarchy for tree views
  5. Database choice: Consider PostgreSQL’s recursive CTEs for complex queries

Error Handling