typeorm/docs/tree-entities.md
Kaveh Fereidouni b91175c59a
Update tree-entities.md
children should be array of categories
2017-12-07 00:30:33 -05:00

1.6 KiB

Tree Entities

TypeORM supports the Adjacency list and Closure table patterns for storing tree structures.

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 tree in once because of join limitations. Example:

import {Entity, Column, PrimaryGeneratedColumn, ManyToOne, OneToMany} from "typeorm";

@Entity()
export class Category {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @Column()
    description: string;

    @ManyToOne(type => Category, category => category.children)
    parent: Category;

    @OneToMany(type => Category, category => category.parent)
    children: Category[];
}
     

Closure table

Closure table stores relations between parent and child in a separate table in a special way. Its efficient in both reads and writes. To learn more about closure table take a look at this awesome presentation by Bill Karwin. Example:

import {ClosureEntity, Column, PrimaryGeneratedColumn, TreeChildren, TreeParent, TreeLevelColumn} from "typeorm";

@ClosureEntity()
export class Category {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @Column()
    description: string;

    @TreeChildren()
    children: Category[];

    @TreeParent()
    parent: Category;

    @TreeLevelColumn()
    level: number;
}