# 树形实体

> 英文标题：Tree Entities
> 官网原文：https://typeorm.io/docs/entity/tree-entities
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 50 块

---

<!-- EN -->
# Tree Entities

<!-- ZH -->
# 树形实体

<!-- EN -->
TypeORM supports the Adjacency list and Closure table patterns for storing tree structures. To learn more about the hierarchy table take a look at [this awesome presentation by Bill Karwin](https://www.slideshare.net/billkarwin/models-for-hierarchical-data).

<!-- ZH -->
TypeORM 支持邻接表（Adjacency list）和闭包表（Closure table）两种存储树形结构的模式。要进一步了解层次表，可以看看 [Bill Karwin 的这份精彩演示](https://www.slideshare.net/billkarwin/models-for-hierarchical-data)。

<!-- EN -->
## Adjacency list

<!-- ZH -->
## 邻接表

<!-- EN -->
Adjacency list is a simple model with self-referencing. Note that TreeRepository doesn't support Adjacency list. 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 [this article by Matthew Schinckel](http://schinckel.net/2014/09/13/long-live-adjacency-lists/). Example:

<!-- ZH -->
邻接表是一种带自引用的简单模型。注意 TreeRepository 不支持邻接表。这种方式的优点是简单，缺点是受连接限制，你无法一次性加载大树。要进一步了解邻接表的优势与用法，请看 [Matthew Schinckel 的这篇文章](http://schinckel.net/2014/09/13/long-live-adjacency-lists/)。示例：

<!-- EN -->
```typescript
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[]
}
```

<!-- ZH -->
```typescript
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[]
}
```

<!-- EN -->
## Nested set

<!-- ZH -->
## 嵌套集

<!-- EN -->
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:

<!-- ZH -->
嵌套集（nested set）是另一种在数据库中存储树形结构的模式。它读起来非常高效，但写起来很差。嵌套集中不能有多个根节点。示例：

<!-- EN -->
```typescript
import {
    Entity,
    Tree,
    Column,
    PrimaryGeneratedColumn,
    TreeChildren,
    TreeParent,
    TreeLevelColumn,
} from "typeorm"

@Entity()
@Tree("nested-set")
export class Category {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @TreeChildren()
    children: Category[]

    @TreeParent()
    parent: Category
}
```

<!-- ZH -->
```typescript
import {
    Entity,
    Tree,
    Column,
    PrimaryGeneratedColumn,
    TreeChildren,
    TreeParent,
    TreeLevelColumn,
} from "typeorm"

@Entity()
@Tree("nested-set")
export class Category {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @TreeChildren()
    children: Category[]

    @TreeParent()
    parent: Category
}
```

<!-- EN -->
## Materialized Path (aka Path Enumeration)

<!-- ZH -->
## 物化路径（又称路径枚举）

<!-- EN -->
Materialized Path (also called Path Enumeration) is another pattern of storing tree structures in the database. It is simple and effective. Example:

<!-- ZH -->
物化路径（Materialized Path，也叫 Path Enumeration）是另一种在数据库中存储树形结构的模式。它简单而有效。示例：

<!-- EN -->
```typescript
import {
    Entity,
    Tree,
    Column,
    PrimaryGeneratedColumn,
    TreeChildren,
    TreeParent,
    TreeLevelColumn,
} from "typeorm"

@Entity()
@Tree("materialized-path")
export class Category {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @TreeChildren()
    children: Category[]

    @TreeParent()
    parent: Category
}
```

<!-- ZH -->
```typescript
import {
    Entity,
    Tree,
    Column,
    PrimaryGeneratedColumn,
    TreeChildren,
    TreeParent,
    TreeLevelColumn,
} from "typeorm"

@Entity()
@Tree("materialized-path")
export class Category {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @TreeChildren()
    children: Category[]

    @TreeParent()
    parent: Category
}
```

<!-- EN -->
## Closure table

<!-- ZH -->
## 闭包表

<!-- EN -->
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:

<!-- ZH -->
闭包表以特殊方式把父子关系存在一张单独的表里。它在读和写两方面都很高效。示例：

<!-- EN -->
```typescript
import {
    Entity,
    Tree,
    Column,
    PrimaryGeneratedColumn,
    TreeChildren,
    TreeParent,
    TreeLevelColumn,
} from "typeorm"

@Entity()
@Tree("closure-table")
export class Category {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @TreeChildren()
    children: Category[]

    @TreeParent()
    parent: Category
}
```

<!-- ZH -->
```typescript
import {
    Entity,
    Tree,
    Column,
    PrimaryGeneratedColumn,
    TreeChildren,
    TreeParent,
    TreeLevelColumn,
} from "typeorm"

@Entity()
@Tree("closure-table")
export class Category {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @TreeChildren()
    children: Category[]

    @TreeParent()
    parent: Category
}
```

<!-- EN -->
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 `descendantColumnName` are callback functions, which receive the primary column's metadata and return the column's name. `closureTableName` is the argument passed to the DataSource's naming strategy's closureJunctionTableName and defaults to parent entity's `tableNameWithoutPrefix`. `closureTableSchema` specifies the schema name where the closure table has to be saved in and defaults to the parent entity's schema (if provided to the parent Entity's decorator options) or the dataSource schema.

<!-- ZH -->
你可以通过给 `@Tree("closure-table", options)` 设置可选参数 `options` 来指定闭包表的表名和/或闭包表的列名。`ancestorColumnName` 和 `descendantColumnName` 是回调函数，它们接收主键列的元数据并返回该列的名称。`closureTableName` 是传给 DataSource 命名策略的 closureJunctionTableName 的参数，默认值是父实体的 `tableNameWithoutPrefix`。`closureTableSchema` 指定闭包表要保存到哪个模式下，默认是父实体的模式（如果在父实体的装饰器选项中提供了），否则是 dataSource 的模式。

<!-- EN -->
```ts
@Tree("closure-table", {
    closureTableName: "category",
    closureTableSchema: "closures_schema",
    ancestorColumnName: (column) => "ancestor_" + column.propertyName,
    descendantColumnName: (column) => "descendant_" + column.propertyName,
})
```

<!-- ZH -->
```ts
@Tree("closure-table", {
    closureTableName: "category",
    closureTableSchema: "closures_schema",
    ancestorColumnName: (column) => "ancestor_" + column.propertyName,
    descendantColumnName: (column) => "descendant_" + column.propertyName,
})
```

<!-- EN -->
## Working with tree entities

<!-- ZH -->
## 操作树形实体

<!-- EN -->
To bind tree entities to each other, it is required to set the parent in the child entity and then save them. for example:

<!-- ZH -->
要把树形实体彼此绑定，需要在子实体中设置父实体，然后保存它们。例如：

<!-- EN -->
```typescript
const a1 = new Category()
a1.name = "a1"
await dataSource.manager.save(a1)

const a11 = new Category()
a11.name = "a11"
a11.parent = a1
await dataSource.manager.save(a11)

const a12 = new Category()
a12.name = "a12"
a12.parent = a1
await dataSource.manager.save(a12)

const a111 = new Category()
a111.name = "a111"
a111.parent = a11
await dataSource.manager.save(a111)

const a112 = new Category()
a112.name = "a112"
a112.parent = a11
await dataSource.manager.save(a112)
```

<!-- ZH -->
```typescript
const a1 = new Category()
a1.name = "a1"
await dataSource.manager.save(a1)

const a11 = new Category()
a11.name = "a11"
a11.parent = a1
await dataSource.manager.save(a11)

const a12 = new Category()
a12.name = "a12"
a12.parent = a1
await dataSource.manager.save(a12)

const a111 = new Category()
a111.name = "a111"
a111.parent = a11
await dataSource.manager.save(a111)

const a112 = new Category()
a112.name = "a112"
a112.parent = a11
await dataSource.manager.save(a112)
```

<!-- EN -->
To load such a tree use `TreeRepository`:

<!-- ZH -->
要加载这样一棵树，请使用 `TreeRepository`：

<!-- EN -->
```typescript
const trees = await dataSource.manager.getTreeRepository(Category).findTrees()
```

<!-- ZH -->
```typescript
const trees = await dataSource.manager.getTreeRepository(Category).findTrees()
```

<!-- EN -->
`trees` will be the following:

<!-- ZH -->
`trees` 将会是下面这样：

<!-- EN -->
```json
[
    {
        "id": 1,
        "name": "a1",
        "children": [
            {
                "id": 2,
                "name": "a11",
                "children": [
                    {
                        "id": 4,
                        "name": "a111"
                    },
                    {
                        "id": 5,
                        "name": "a112"
                    }
                ]
            },
            {
                "id": 3,
                "name": "a12"
            }
        ]
    }
]
```

<!-- ZH -->
```json
[
    {
        "id": 1,
        "name": "a1",
        "children": [
            {
                "id": 2,
                "name": "a11",
                "children": [
                    {
                        "id": 4,
                        "name": "a111"
                    },
                    {
                        "id": 5,
                        "name": "a112"
                    }
                ]
            },
            {
                "id": 3,
                "name": "a12"
            }
        ]
    }
]
```

<!-- EN -->
There are other special methods to work with tree entities through `TreeRepository`:

<!-- ZH -->
通过 `TreeRepository` 操作树形实体还有其他一些特殊方法：

<!-- EN -->
* `findTrees` - Returns all trees in the database with all their children, children of children, etc.

<!-- ZH -->
* `findTrees` - 返回数据库中的所有树，包含它们的所有子节点、子节点的子节点等。

<!-- EN -->
```typescript
const treeCategories = await dataSource.manager
    .getTreeRepository(Category)
    .findTrees()
// returns root categories with sub categories inside

const treeCategoriesWithLimitedDepth = await dataSource.manager
    .getTreeRepository(Category)
    .findTrees({ depth: 2 })
// returns root categories with sub categories inside, up to depth 2
```

<!-- ZH -->
```typescript
const treeCategories = await dataSource.manager
    .getTreeRepository(Category)
    .findTrees()
// 返回根分类，其中包含子分类

const treeCategoriesWithLimitedDepth = await dataSource.manager
    .getTreeRepository(Category)
    .findTrees({ depth: 2 })
// 返回根分类，其中包含子分类，最多到深度 2
```

<!-- EN -->
* `findRoots` - Roots are entities that have no ancestors. Finds them all. Does not load children's leaves.

<!-- ZH -->
* `findRoots` - 根节点是没有祖先的实体。找出所有根节点。不会加载子节点的叶子。

<!-- EN -->
```typescript
const rootCategories = await dataSource.manager
    .getTreeRepository(Category)
    .findRoots()
// returns root categories without sub categories inside
```

<!-- ZH -->
```typescript
const rootCategories = await dataSource.manager
    .getTreeRepository(Category)
    .findRoots()
// 返回根分类，其中不包含子分类
```

<!-- EN -->
* `findDescendants` - Gets all children (descendants) of the given entity. Returns them all in a flat array.

<!-- ZH -->
* `findDescendants` - 获取给定实体的所有子节点（后代）。以扁平数组形式全部返回。

<!-- EN -->
```typescript
const children = await dataSource.manager
    .getTreeRepository(Category)
    .findDescendants(parentCategory)
// returns all direct subcategories (without its nested categories) of a parentCategory
```

<!-- ZH -->
```typescript
const children = await dataSource.manager
    .getTreeRepository(Category)
    .findDescendants(parentCategory)
// 返回 parentCategory 的所有直接子分类（不含其嵌套分类）
```

<!-- EN -->
* `findDescendantsTree` - Gets all children (descendants) of the given entity. Returns them in a tree - nested into each other.

<!-- ZH -->
* `findDescendantsTree` - 获取给定实体的所有子节点（后代）。以树的形式返回——彼此嵌套。

<!-- EN -->
```typescript
const childrenTree = await repository.findDescendantsTree(parentCategory)
// returns all direct subcategories (with its nested categories) of a parentCategory
const childrenTreeWithLimitedDepth = await repository.findDescendantsTree(
    parentCategory,
    { depth: 2 },
)
// returns all direct subcategories (with its nested categories) of a parentCategory, up to depth 2
```

<!-- ZH -->
```typescript
const childrenTree = await repository.findDescendantsTree(parentCategory)
// 返回 parentCategory 的所有直接子分类（含其嵌套分类）
const childrenTreeWithLimitedDepth = await repository.findDescendantsTree(
    parentCategory,
    { depth: 2 },
)
// 返回 parentCategory 的所有直接子分类（含其嵌套分类），最多到深度 2
```

<!-- EN -->
* `createDescendantsQueryBuilder` - Creates a query builder used to get descendants of the entities in a tree.

<!-- ZH -->
* `createDescendantsQueryBuilder` - 创建一个 query builder，用于获取树中实体的后代。

<!-- EN -->
```typescript
const children = await repository
    .createDescendantsQueryBuilder(
        "category",
        "categoryClosure",
        parentCategory,
    )
    .andWhere("category.type = 'secondary'")
    .getMany()
```

<!-- ZH -->
```typescript
const children = await repository
    .createDescendantsQueryBuilder(
        "category",
        "categoryClosure",
        parentCategory,
    )
    .andWhere("category.type = 'secondary'")
    .getMany()
```

<!-- EN -->
* `countDescendants` - Gets the number of descendants of the entity.

<!-- ZH -->
* `countDescendants` - 获取该实体的后代数量。

<!-- EN -->
```typescript
const childrenCount = await dataSource.manager
    .getTreeRepository(Category)
    .countDescendants(parentCategory)
```

<!-- ZH -->
```typescript
const childrenCount = await dataSource.manager
    .getTreeRepository(Category)
    .countDescendants(parentCategory)
```

<!-- EN -->
* `findAncestors` - Gets all parents (ancestors) of the given entity. Returns them all in a flat array.

<!-- ZH -->
* `findAncestors` - 获取给定实体的所有父节点（祖先）。以扁平数组形式全部返回。

<!-- EN -->
```typescript
const parents = await repository.findAncestors(childCategory)
// returns all direct childCategory's parent categories (without "parent of parents")
```

<!-- ZH -->
```typescript
const parents = await repository.findAncestors(childCategory)
// 返回 childCategory 的所有直接父分类（不含"父节点的父节点"）
```

<!-- EN -->
* `findAncestorsTree` - Gets all parents (ancestors) of the given entity. Returns them in a tree - nested into each other.

<!-- ZH -->
* `findAncestorsTree` - 获取给定实体的所有父节点（祖先）。以树的形式返回——彼此嵌套。

<!-- EN -->
```typescript
const parentsTree = await dataSource.manager
    .getTreeRepository(Category)
    .findAncestorsTree(childCategory)
// returns all direct childCategory's parent categories (with "parent of parents")
```

<!-- ZH -->
```typescript
const parentsTree = await dataSource.manager
    .getTreeRepository(Category)
    .findAncestorsTree(childCategory)
// 返回 childCategory 的所有直接父分类（含"父节点的父节点"）
```

<!-- EN -->
* `createAncestorsQueryBuilder` - Creates a query builder used to get the ancestors of the entities in a tree.

<!-- ZH -->
* `createAncestorsQueryBuilder` - 创建一个 query builder，用于获取树中实体的祖先。

<!-- EN -->
```typescript
const parents = await repository
    .createAncestorsQueryBuilder("category", "categoryClosure", childCategory)
    .andWhere("category.type = 'secondary'")
    .getMany()
```

<!-- ZH -->
```typescript
const parents = await repository
    .createAncestorsQueryBuilder("category", "categoryClosure", childCategory)
    .andWhere("category.type = 'secondary'")
    .getMany()
```

<!-- EN -->
* `countAncestors` - Gets the number of ancestors of the entity.

<!-- ZH -->
* `countAncestors` - 获取该实体的祖先数量。

<!-- EN -->
```typescript
const parentsCount = await dataSource.manager
    .getTreeRepository(Category)
    .countAncestors(childCategory)
```

<!-- ZH -->
```typescript
const parentsCount = await dataSource.manager
    .getTreeRepository(Category)
    .countAncestors(childCategory)
```

<!-- EN -->
For the following methods, options can be passed:

<!-- ZH -->
以下方法可以传入选项：

<!-- EN -->
* findTrees
* findRoots
* findDescendants
* findDescendantsTree
* findAncestors
* findAncestorsTree

<!-- ZH -->
* findTrees
* findRoots
* findDescendants
* findDescendantsTree
* findAncestors
* findAncestorsTree

<!-- EN -->
The following options are available:

<!-- ZH -->
可用的选项如下：

<!-- EN -->
* `relations` - Indicates what relations of entity should be loaded (simplified left join form).

<!-- ZH -->
* `relations` - 表示应加载实体的哪些关系（简化的左连接形式）。

<!-- EN -->
Examples:

<!-- ZH -->
示例：

<!-- EN -->
```typescript
const treeCategoriesWithRelations = await dataSource.manager
    .getTreeRepository(Category)
    .findTrees({
        relations: ["sites"],
    })
// automatically joins the sites relation

const parentsWithRelations = await dataSource.manager
    .getTreeRepository(Category)
    .findAncestors(childCategory, {
        relations: ["members"],
    })
// returns all direct childCategory's parent categories (without "parent of parents") and joins the 'members' relation
```

<!-- ZH -->
```typescript
const treeCategoriesWithRelations = await dataSource.manager
    .getTreeRepository(Category)
    .findTrees({
        relations: ["sites"],
    })
// 自动连接 sites 关系

const parentsWithRelations = await dataSource.manager
    .getTreeRepository(Category)
    .findAncestors(childCategory, {
        relations: ["members"],
    })
// 返回 childCategory 的所有直接父分类（不含"父节点的父节点"），并连接 'members' 关系
```
