Tree Entities
Last updated
Last updated
TypeORM supports the Adjacency list and Closure table patterns for storing tree structures. To learn more about the hierarchy table take a look at .
Adjacency list is a simple model with self-referencing. The benefit of this approach is simplicity, a drawback is that you can't load big trees all at once because of join limitations. To learn more about the benefits and use of Adjacency Lists look at . Example:
Nested set is another pattern of storing tree structures in the database. It is very efficient for reads, but bad for writes. You cannot have multiple roots in the nested set. Example:
Materialized Path (also called Path Enumeration) is another pattern of storing tree structures in the database. It is simple and effective. Example:
Closure table stores relations between parent and child in a separate table in a special way. It's efficient in both reading and writing. Example:
You can specify the closure table name and/or closure table column names by setting optional parameter options
into @Tree("closure-table", options)
. ancestorColumnName
and descandantColumnName
are callback functions, which receive the primary column's metadata and return the column's name.
To bind tree entities to each other, it is required to set the parent in the child entity and then save them. for example:
To load such a tree use TreeRepository
:
trees
will be the following:
There are other special methods to work with tree entities through TreeRepository
:
findTrees
- Returns all trees in the database with all their children, children of children, etc.
findRoots
- Roots are entities that have no ancestors. Finds them all. Does not load children's leaves.
findDescendants
- Gets all children (descendants) of the given entity. Returns them all in a flat array.
findDescendantsTree
- Gets all children (descendants) of the given entity. Returns them in a tree - nested into each other.
createDescendantsQueryBuilder
- Creates a query builder used to get descendants of the entities in a tree.
countDescendants
- Gets the number of descendants of the entity.
findAncestors
- Gets all parents (ancestors) of the given entity. Returns them all in a flat array.
findAncestorsTree
- Gets all parents (ancestors) of the given entity. Returns them in a tree - nested into each other.
createAncestorsQueryBuilder
- Creates a query builder used to get the ancestors of the entities in a tree.
countAncestors
- Gets the number of ancestors of the entity.
For the following methods, options can be passed:
findTrees
findRoots
findDescendants
findDescendantsTree
findAncestors
findAncestorsTree
The following options are available:
relations
- Indicates what relations of entity should be loaded (simplified left join form).
Examples: