# 关系

> 英文标题：Relations
> 官网原文：https://typeorm.io/docs/relations/relations
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 45 块

---

<!-- EN -->
# Relations

<!-- ZH -->
# 关系

<!-- EN -->
## What are relations?

<!-- ZH -->
## 什么是关系？

<!-- EN -->
Relations helps you to work with related entities easily. There are several types of relations:

<!-- ZH -->
关系能让你轻松地处理相关联的实体。关系有几种类型：

<!-- EN -->
* [one-to-one](https://typeorm.io/docs/relations/one-to-one-relations) using `@OneToOne`
* [many-to-one](https://typeorm.io/docs/relations/many-to-one-one-to-many-relations) using `@ManyToOne`
* [one-to-many](https://typeorm.io/docs/relations/many-to-one-one-to-many-relations) using `@OneToMany`
* [many-to-many](https://typeorm.io/docs/relations/many-to-many-relations) using `@ManyToMany`

<!-- ZH -->
* 使用 `@OneToOne` 的[一对一](https://typeorm.io/docs/relations/one-to-one-relations)
* 使用 `@ManyToOne` 的[多对一](https://typeorm.io/docs/relations/many-to-one-one-to-many-relations)
* 使用 `@OneToMany` 的[一对多](https://typeorm.io/docs/relations/many-to-one-one-to-many-relations)
* 使用 `@ManyToMany` 的[多对多](https://typeorm.io/docs/relations/many-to-many-relations)

<!-- EN -->
## Relation options

<!-- ZH -->
## 关系选项

<!-- EN -->
There are several options you can specify for relations:

<!-- ZH -->
你可以为关系指定若干选项：

<!-- EN -->
* `eager: boolean` (default: `false`) - If set to true, the relation will always be loaded with the main entity when using `find*` methods or `QueryBuilder` on this entity

<!-- ZH -->
* `eager: boolean`（默认：`false`）- 设为 true 时，在该实体上使用 `find*` 方法或 `QueryBuilder` 时，这个关系总会随主实体一起加载

<!-- EN -->
* `cascade: boolean | ("insert" | "update")[]` (default: `false`) - If set to true, the related object will be inserted and updated in the database. You can also specify an array of [cascade options](#cascade-options).

<!-- ZH -->
* `cascade: boolean | ("insert" | "update")[]`（默认：`false`）- 设为 true 时，关联对象会在数据库中被插入和更新。你也可以指定一个[级联选项](#cascade-options)数组。

<!-- EN -->
* `onDelete: "RESTRICT"|"CASCADE"|"SET NULL"` (default: `RESTRICT`) - specifies how foreign key should behave when referenced object is deleted

<!-- ZH -->
* `onDelete: "RESTRICT"|"CASCADE"|"SET NULL"`（默认：`RESTRICT`）- 指定被引用对象被删除时外键应如何表现

<!-- EN -->
* `deferrable: "INITIALLY DEFERRED"|"INITIALLY IMMEDIATE"` - When set, foreign key constraints are deferrable (e.g. validated at commit time). For many-to-many relations this applies to both junction-table foreign keys. Supported on PostgreSQL, better-sqlite3, and SAP HANA.

<!-- ZH -->
* `deferrable: "INITIALLY DEFERRED"|"INITIALLY IMMEDIATE"` - 设置后，外键约束变为可延迟的（例如在提交时校验）。对多对多关系，它同时作用于中间表的两个外键。在 PostgreSQL、better-sqlite3 和 SAP HANA 上受支持。

<!-- EN -->
* `nullable: boolean` (default: `true`) - Indicates whether this relation's column is nullable or not. By default it is nullable. For `ManyToOne` and owning `OneToOne` relations, setting `nullable: false` also causes TypeORM to use `INNER JOIN` instead of `LEFT JOIN` when loading the relation, since the related entity is guaranteed to exist.

<!-- ZH -->
* `nullable: boolean`（默认：`true`）- 表示该关系的列是否可空。默认是可空的。对 `ManyToOne` 和拥有方 `OneToOne` 关系，设置 `nullable: false` 还会让 TypeORM 在加载该关系时使用 `INNER JOIN` 而不是 `LEFT JOIN`，因为关联实体必然存在。

<!-- EN -->
* `orphanedRowAction: "nullify" | "delete" | "soft-delete" | "disable"` (default: `nullify`) - When a parent is saved (cascading enabled) without a child/children that still exists in database, this will control what shall happen to them.

<!-- ZH -->
* `orphanedRowAction: "nullify" | "delete" | "soft-delete" | "disable"`（默认：`nullify`）- 当保存父对象（已启用级联）时，数据库中仍然存在的某个子对象 / 某些子对象不在其中，该选项控制如何处理它们。

<!-- EN -->
  <!-- -->

<!-- ZH -->
  <!-- -->

<!-- EN -->
  * *nullify* will remove the relation key. If the foreign key column is non-nullable, the orphaned row will be deleted instead since it cannot be set to `null`.
  * *delete* will remove these children from database.
  * *soft-delete* will mark children as soft-deleted.
  * *disable* will keep the relation intact. To delete, one has to use their own repository.

<!-- ZH -->
  * *nullify* 会移除关系键。如果外键列不可空，孤儿行会被删除，因为它无法被设为 `null`。
  * *delete* 会从数据库中删除这些子对象。
  * *soft-delete* 会把子对象标记为软删除。
  * *disable* 会保持关系不变。要删除的话，必须使用它们自己的 repository。

<!-- EN -->
## Cascades

<!-- ZH -->
## 级联

<!-- EN -->
Cascades example:

<!-- ZH -->
级联示例：

<!-- EN -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column, ManyToMany } from "typeorm"
import { Question } from "./Question"

@Entity()
export class Category {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @ManyToMany((type) => Question, (question) => question.categories)
    questions: Question[]
}
```

<!-- ZH -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column, ManyToMany } from "typeorm"
import { Question } from "./Question"

@Entity()
export class Category {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @ManyToMany((type) => Question, (question) => question.categories)
    questions: Question[]
}
```

<!-- EN -->
```typescript
import {
    Entity,
    PrimaryGeneratedColumn,
    Column,
    ManyToMany,
    JoinTable,
} from "typeorm"
import { Category } from "./Category"

@Entity()
export class Question {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    title: string

    @Column()
    text: string

    @ManyToMany((type) => Category, (category) => category.questions, {
        cascade: true,
    })
    @JoinTable()
    categories: Category[]
}
```

<!-- ZH -->
```typescript
import {
    Entity,
    PrimaryGeneratedColumn,
    Column,
    ManyToMany,
    JoinTable,
} from "typeorm"
import { Category } from "./Category"

@Entity()
export class Question {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    title: string

    @Column()
    text: string

    @ManyToMany((type) => Category, (category) => category.questions, {
        cascade: true,
    })
    @JoinTable()
    categories: Category[]
}
```

<!-- EN -->
```typescript
const category1 = new Category()
category1.name = "ORMs"

const category2 = new Category()
category2.name = "Programming"

const question = new Question()
question.title = "How to ask questions?"
question.text = "Where can I ask TypeORM-related questions?"
question.categories = [category1, category2]
await dataSource.manager.save(question)
```

<!-- ZH -->
```typescript
const category1 = new Category()
category1.name = "ORMs"

const category2 = new Category()
category2.name = "Programming"

const question = new Question()
question.title = "How to ask questions?"
question.text = "Where can I ask TypeORM-related questions?"
question.categories = [category1, category2]
await dataSource.manager.save(question)
```

<!-- EN -->
As you can see in this example we did not call `save` for `category1` and `category2`. They will be automatically inserted, because we set `cascade` to true.

<!-- ZH -->
如你所见，在这个示例中我们并没有为 `category1` 和 `category2` 调用 `save`。它们会被自动插入，因为我们把 `cascade` 设成了 true。

<!-- EN -->
Keep in mind - great power comes with great responsibility. Cascades may seem like a good and easy way to work with relations, but they may also bring bugs and security issues when some undesired object is being saved into the database. Also, they provide a less explicit way of saving new objects into the database.

<!-- ZH -->
请记住——能力越大，责任越大。级联看起来是处理关系的一种又好又简单的方式，但当某个不该被保存的对象被存进数据库时，它也可能带来 bug 和安全问题。此外，它让"把新对象保存进数据库"这件事变得不那么显式。

<!-- EN -->
### Cascade Options

<!-- ZH -->
### 级联选项

<!-- EN -->
The `cascade` option can be set as a `boolean` or an array of cascade options `("insert" | "update" | "remove" | "soft-remove" | "recover")[]`.

<!-- ZH -->
`cascade` 选项可以设为 `boolean`，也可以设为级联选项数组 `("insert" | "update" | "remove" | "soft-remove" | "recover")[]`。

<!-- EN -->
It will default to `false`, meaning no cascades. Setting `cascade: true` will enable full cascades. You can also specify options by providing an array.

<!-- ZH -->
它默认为 `false`，即不启用任何级联。设置 `cascade: true` 会启用完整级联。你也可以通过提供数组来指定具体选项。

<!-- EN -->
For example:

<!-- ZH -->
例如：

<!-- EN -->
```typescript
@Entity(Post)
export class Post {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    title: string

    @Column()
    text: string

    // Full cascades on categories.
    @ManyToMany((type) => PostCategory, {
        cascade: true,
    })
    @JoinTable()
    categories: PostCategory[]

    // Cascade insert here means if there is a new PostDetails instance set
    // on this relation, it will be inserted automatically to the db when you save this Post entity
    @ManyToMany((type) => PostDetails, (details) => details.posts, {
        cascade: ["insert"],
    })
    @JoinTable()
    details: PostDetails[]

    // Cascade update here means if there are changes to an existing PostImage, it
    // will be updated automatically to the db when you save this Post entity
    @ManyToMany((type) => PostImage, (image) => image.posts, {
        cascade: ["update"],
    })
    @JoinTable()
    images: PostImage[]

    // Cascade insert & update here means if there are new PostInformation instances
    // or an update to an existing one, they will be automatically inserted or updated
    // when you save this Post entity
    @ManyToMany((type) => PostInformation, (information) => information.posts, {
        cascade: ["insert", "update"],
    })
    @JoinTable()
    informations: PostInformation[]
}
```

<!-- ZH -->
```typescript
@Entity(Post)
export class Post {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    title: string

    @Column()
    text: string

    // 对 categories 启用完整级联。
    @ManyToMany((type) => PostCategory, {
        cascade: true,
    })
    @JoinTable()
    categories: PostCategory[]

    // 这里的级联插入意味着，如果该关系上设置了新的 PostDetails 实例，
    // 保存这个 Post 实体时它会被自动插入数据库
    @ManyToMany((type) => PostDetails, (details) => details.posts, {
        cascade: ["insert"],
    })
    @JoinTable()
    details: PostDetails[]

    // 这里的级联更新意味着，如果已有的 PostImage 发生了变化，
    // 保存这个 Post 实体时它会被自动更新到数据库
    @ManyToMany((type) => PostImage, (image) => image.posts, {
        cascade: ["update"],
    })
    @JoinTable()
    images: PostImage[]

    // 这里的级联插入与更新意味着，如果出现了新的 PostInformation 实例
    // 或已有的实例被更新，它们会在保存这个 Post 实体时被自动插入或更新
    @ManyToMany((type) => PostInformation, (information) => information.posts, {
        cascade: ["insert", "update"],
    })
    @JoinTable()
    informations: PostInformation[]
}
```

<!-- EN -->
Cascade remove

<!-- ZH -->
级联删除

<!-- EN -->
When using `cascade: ["remove"]` or `cascade: true`, calling `manager.remove(entity)` will also remove related entities that are loaded on the entity instance. TypeORM only traverses relations that are populated on the object — if a relation is not loaded, its children will not be cascade-removed. Make sure to load relations before removing:

<!-- ZH -->
使用 `cascade: ["remove"]` 或 `cascade: true` 时，调用 `manager.remove(entity)` 也会删除该实体实例上已加载的关联实体。TypeORM 只会遍历对象上已填充的关系——如果某个关系没有被加载，它的子对象不会被级联删除。请确保在删除前先加载关系：

<!-- EN -->
```typescript
const post = await manager.findOne(Post, {
    where: { id: 1 },
    relations: { categories: true },
})
await manager.remove(post) // categories will also be removed
```

<!-- ZH -->
```typescript
const post = await manager.findOne(Post, {
    where: { id: 1 },
    relations: { categories: true },
})
await manager.remove(post) // categories 也会被删除
```

<!-- EN -->
## `@JoinColumn` options

<!-- ZH -->
## `@JoinColumn` 选项

<!-- EN -->
`@JoinColumn` not only defines which side of the relation contains the join column with a foreign key, but also allows you to customize join column name and referenced column name.

<!-- ZH -->
`@JoinColumn` 不仅定义了关系的哪一侧持有带外键的连接列，还允许你自定义连接列名和被引用列名。

<!-- EN -->
When we set `@JoinColumn`, it automatically creates a column in the database named `propertyName + referencedColumnName`. For example:

<!-- ZH -->
当我们设置 `@JoinColumn` 时，它会自动在数据库中创建一个名为 `propertyName + referencedColumnName` 的列。例如：

<!-- EN -->
```typescript
@ManyToOne(type => Category)
@JoinColumn() // this decorator is optional for @ManyToOne, but required for @OneToOne
category: Category;
```

<!-- ZH -->
```typescript
@ManyToOne(type => Category)
@JoinColumn() // 这个装饰器对 @ManyToOne 是可选的，但对 @OneToOne 是必需的
category: Category;
```

<!-- EN -->
This code will create a `categoryId` column in the database. If you want to change this name in the database you can specify a custom join column name:

<!-- ZH -->
这段代码会在数据库中创建一个 `categoryId` 列。如果你想改变它在数据库中的名字，可以指定自定义的连接列名：

<!-- EN -->
```typescript
@ManyToOne(type => Category)
@JoinColumn({ name: "cat_id" })
category: Category;
```

<!-- ZH -->
```typescript
@ManyToOne(type => Category)
@JoinColumn({ name: "cat_id" })
category: Category;
```

<!-- EN -->
Join columns are always a reference to some other columns (using a foreign key). By default your relation always refers to the primary column of the related entity. If you want to create relation with other columns of the related entity - you can specify them in `@JoinColumn` as well:

<!-- ZH -->
连接列总是对其他某些列的引用（通过外键）。默认情况下，你的关系总是引用关联实体的主键列。如果你想与关联实体的其他列建立关系，也可以在 `@JoinColumn` 中指定它们：

<!-- EN -->
```typescript
@ManyToOne(type => Category)
@JoinColumn({ referencedColumnName: "name" })
category: Category;
```

<!-- ZH -->
```typescript
@ManyToOne(type => Category)
@JoinColumn({ referencedColumnName: "name" })
category: Category;
```

<!-- EN -->
The relation now refers to `name` of the `Category` entity, instead of `id`. Column name for that relation will become `categoryName`.

<!-- ZH -->
此时该关系引用的是 `Category` 实体的 `name`，而不是 `id`。该关系的列名会变成 `categoryName`。

<!-- EN -->
You can also join multiple columns. Note that they do not reference the primary column of the related entity by default: you must provide the referenced column name.

<!-- ZH -->
你也可以连接多个列。注意它们默认并不引用关联实体的主键列：你必须提供被引用的列名。

<!-- EN -->
```typescript
@ManyToOne(type => Category)
@JoinColumn([
    { name: "category_id", referencedColumnName: "id" },
    { name: "locale_id", referencedColumnName: "locale_id" }
])
category: Category;
```

<!-- ZH -->
```typescript
@ManyToOne(type => Category)
@JoinColumn([
    { name: "category_id", referencedColumnName: "id" },
    { name: "locale_id", referencedColumnName: "locale_id" }
])
category: Category;
```

<!-- EN -->
> **Note:** When using composite `@JoinColumn` or `@JoinTable`, TypeORM automatically sorts the foreign key columns to match the referenced entity's primary key order. This ensures compatibility with databases like MySQL, MSSQL, and SAP HANA that require FK columns to reference PK columns in index order.

<!-- ZH -->
> **注意：** 使用复合 `@JoinColumn` 或 `@JoinTable` 时，TypeORM 会自动对外键列排序，使其与被引用实体的主键顺序一致。这能保证与 MySQL、MSSQL 和 SAP HANA 这类要求外键列按索引顺序引用主键列的数据库兼容。

<!-- EN -->
## `@JoinTable` options

<!-- ZH -->
## `@JoinTable` 选项

<!-- EN -->
`@JoinTable` is used for `many-to-many` relations and describes join columns of the "junction" table. A junction table is a special separate table created automatically by TypeORM with columns that refer to the related entities. You can change column names inside junction tables and their referenced columns with `@JoinColumn`: You can also change the name of the generated "junction" table.

<!-- ZH -->
`@JoinTable` 用于 `many-to-many` 关系，描述"中间表"的连接列。中间表是 TypeORM 自动创建的一张特殊独立表，其中的列引用相关联的实体。你可以用 `@JoinColumn` 修改中间表中的列名及其被引用列，也可以修改生成的"中间表"的表名。

<!-- EN -->
```typescript
@ManyToMany(type => Category)
@JoinTable({
    name: "question_categories", // table name for the junction table of this relation
    joinColumn: {
        name: "question",
        referencedColumnName: "id"
    },
    inverseJoinColumn: {
        name: "category",
        referencedColumnName: "id"
    }
})
categories: Category[];
```

<!-- ZH -->
```typescript
@ManyToMany(type => Category)
@JoinTable({
    name: "question_categories", // 该关系中间表的表名
    joinColumn: {
        name: "question",
        referencedColumnName: "id"
    },
    inverseJoinColumn: {
        name: "category",
        referencedColumnName: "id"
    }
})
categories: Category[];
```

<!-- EN -->
If the destination table has composite primary keys, then an array of properties must be sent to `@JoinTable`.

<!-- ZH -->
如果目标表有复合主键，那么必须给 `@JoinTable` 传入一个属性数组。
