Tree Entities

TypeORM supports the Adjacency list and Closure table patterns for storing tree structures.To learn more about hierarchy table take a look at this awesome presentation by Bill Karwin.

Adjacency list

Adjacency list is a simple model with self-referencing.The benefit of this approach is simplicity,drawback is that you can’t load big trees in all at once because of join limitations.To learn more about the benefits and use of Adjacency Lists look at this article by Matthew Schinckel.Example:

  1. import {Entity, Column, PrimaryGeneratedColumn, ManyToOne, OneToMany} from "typeorm";
  2. @Entity()
  3. export class Category {
  4. @PrimaryGeneratedColumn()
  5. id: number;
  6. @Column()
  7. name: string;
  8. @Column()
  9. description: string;
  10. @ManyToOne(type => Category, category => category.children)
  11. parent: Category;
  12. @OneToMany(type => Category, category => category.parent)
  13. children: Category[];
  14. }

Nested set

Nested set is another pattern of storing tree structures in the database.Its very efficient for reads, but bad for writes.You cannot have multiple roots in nested set.Example:

  1. import {Entity, Tree, Column, PrimaryGeneratedColumn, TreeChildren, TreeParent, TreeLevelColumn} from "typeorm";
  2. @Entity()
  3. @Tree("nested-set")
  4. export class Category {
  5. @PrimaryGeneratedColumn()
  6. id: number;
  7. @Column()
  8. name: string;
  9. @TreeChildren()
  10. children: Category[];
  11. @TreeParent()
  12. parent: Category;
  13. }

Materialized Path (aka Path Enumeration)

Materialized Path (also called Path Enumeration) is another pattern of storing tree structures in the database.Its simple and effective.Example:

  1. import {Entity, Tree, Column, PrimaryGeneratedColumn, TreeChildren, TreeParent, TreeLevelColumn} from "typeorm";
  2. @Entity()
  3. @Tree("materialized-path")
  4. export class Category {
  5. @PrimaryGeneratedColumn()
  6. id: number;
  7. @Column()
  8. name: string;
  9. @TreeChildren()
  10. children: Category[];
  11. @TreeParent()
  12. parent: Category;
  13. }

Closure table

Closure table stores relations between parent and child in a separate table in a special way.It’s efficient in both reads and writes.Example:

  1. import {Entity, Tree, Column, PrimaryGeneratedColumn, TreeChildren, TreeParent, TreeLevelColumn} from "typeorm";
  2. @Entity()
  3. @Tree("closure-table")
  4. export class Category {
  5. @PrimaryGeneratedColumn()
  6. id: number;
  7. @Column()
  8. name: string;
  9. @TreeChildren()
  10. children: Category[];
  11. @TreeParent()
  12. parent: Category;
  13. }

Working with tree entities

To make bind tree entities to each other its important to set to children entities their parent and save them,for example:

  1. const manager = getManager();
  2. const a1 = new Category("a1");
  3. a1.name = "a1";
  4. await manager.save(a1);
  5. const a11 = new Category();
  6. a11.name = "a11";
  7. a11.parent = a1;
  8. await manager.save(a11);
  9. const a12 = new Category();
  10. a12.name = "a12";
  11. a12.parent = a1;
  12. await manager.save(a12);
  13. const a111 = new Category();
  14. a111.name = "a111";
  15. a111.parent = a11;
  16. await manager.save(a111);
  17. const a112 = new Category();
  18. a112.name = "a112";
  19. a112.parent = a11;
  20. await manager.save(a112);

To load such a tree use TreeRepository:

  1. const manager = getManager();
  2. const trees = await manager.getTreeRepository(Category).findTrees();

trees will be following:

  1. [{
  2. "id": 1,
  3. "name": "a1",
  4. "children": [{
  5. "id": 2,
  6. "name": "a11",
  7. "children": [{
  8. "id": 4,
  9. "name": "a111"
  10. }, {
  11. "id": 5,
  12. "name": "a112"
  13. }]
  14. }, {
  15. "id": 3,
  16. "name": "a12"
  17. }]
  18. }]

There are other special methods to work with tree entities thought TreeRepository:

  • findTrees - Returns all trees in the database with all their children, children of children, etc.
  1. const treeCategories = await repository.findTrees();
  2. // returns root categories with sub categories inside
  • findRoots - Roots are entities that have no ancestors. Finds them all.Does not load children leafs.
  1. const rootCategories = await repository.findRoots();
  2. // returns root categories without sub categories inside
  • findDescendants - Gets all children (descendants) of the given entity. Returns them all in a flat array.
  1. const children = await repository.findDescendants(parentCategory);
  2. // returns all direct subcategories (without its nested categories) of a parentCategory
  • findDescendantsTree - Gets all children (descendants) of the given entity. Returns them in a tree - nested into each other.
  1. const childrenTree = await repository.findDescendantsTree(parentCategory);
  2. // returns all direct subcategories (with its nested categories) of a parentCategory
  • createDescendantsQueryBuilder - Creates a query builder used to get descendants of the entities in a tree.
  1. const children = await repository
  2. .createDescendantsQueryBuilder("category", "categoryClosure", parentCategory)
  3. .andWhere("category.type = 'secondary'")
  4. .getMany();
  • countDescendants - Gets number of descendants of the entity.
  1. const childrenCount = await repository.countDescendants(parentCategory);
  • findAncestors - Gets all parent (ancestors) of the given entity. Returns them all in a flat array.
  1. const parents = await repository.findAncestors(childCategory);
  2. // returns all direct childCategory's parent categories (without "parent of parents")
  • findAncestorsTree - Gets all parent (ancestors) of the given entity. Returns them in a tree - nested into each other.
  1. const parentsTree = await repository.findAncestorsTree(childCategory);
  2. // returns all direct childCategory's parent categories (with "parent of parents")
  • createAncestorsQueryBuilder - Creates a query builder used to get ancestors of the entities in a tree.
  1. const parents = await repository
  2. .createAncestorsQueryBuilder("category", "categoryClosure", childCategory)
  3. .andWhere("category.type = 'secondary'")
  4. .getMany();
  • countAncestors - Gets the number of ancestors of the entity.
  1. const parentsCount = await repository.countAncestors(childCategory);