# 急加载与懒加载关系

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

---

<!-- EN -->
# Eager and Lazy Relations

<!-- ZH -->
# 急加载与懒加载关系

<!-- EN -->
## Eager relations

<!-- ZH -->
## 急加载关系

<!-- EN -->
Eager relations are loaded automatically each time you load entities from the database. For 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, {
        eager: 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, {
        eager: true,
    })
    @JoinTable()
    categories: Category[]
}
```

<!-- EN -->
Now when you load questions you don't need to join or specify relations you want to load. They will be loaded automatically:

<!-- ZH -->
现在当你加载问题时，不需要连接或指定想要加载的关系。它们会被自动加载：

<!-- EN -->
```typescript
const questionRepository = dataSource.getRepository(Question)

// questions will be loaded with its categories
const questions = await questionRepository.find()
```

<!-- ZH -->
```typescript
const questionRepository = dataSource.getRepository(Question)

// questions 会连同它的 categories 一起被加载
const questions = await questionRepository.find()
```

<!-- EN -->
Eager relations only work when you use `find*` methods. If you use `QueryBuilder` eager relations are disabled and have to use `leftJoinAndSelect` to load the relation. Eager relations can only be used on one side of the relationship, using `eager: true` on both sides of relationship is disallowed.

<!-- ZH -->
急加载关系只在你使用 `find*` 方法时生效。如果使用 `QueryBuilder`，急加载关系会被禁用，你必须用 `leftJoinAndSelect` 来加载该关系。急加载关系只能在关系的一侧使用，在关系两侧都使用 `eager: true` 是不被允许的。

<!-- EN -->
By default, eager relations are loaded using `LEFT JOIN`. If the relation is also marked `nullable: false` (and it owns the join column, i.e. `ManyToOne` or owning `OneToOne`), TypeORM uses `INNER JOIN` instead, which can produce more efficient query plans.

<!-- ZH -->
默认情况下，急加载关系使用 `LEFT JOIN` 加载。如果该关系同时被标记为 `nullable: false`（并且它持有连接列，即 `ManyToOne` 或拥有方 `OneToOne`），TypeORM 会改用 `INNER JOIN`，这能产生更高效的查询计划。

<!-- EN -->
### Relation load strategy

<!-- ZH -->
### 关系加载策略

<!-- EN -->
By default, eager relations are loaded by adding SQL JOINs to the main query (`"join"` strategy). If you are loading too much data with nested joins, you can switch to the `"query"` strategy, which loads relations via separate database queries instead:

<!-- ZH -->
默认情况下，急加载关系通过给主查询添加 SQL JOIN 来加载（`"join"` 策略）。如果嵌套连接加载的数据太多，你可以切换到 `"query"` 策略，它改为通过独立的数据库查询来加载关系：

<!-- EN -->
```typescript
// per-query
const questions = await questionRepository.find({
    relationLoadStrategy: "query",
})

// or set as the default for the entire DataSource
const dataSource = new DataSource({
    // ...
    relationLoadStrategy: "query",
})
```

<!-- ZH -->
```typescript
// 按单次查询设置
const questions = await questionRepository.find({
    relationLoadStrategy: "query",
})

// 或者设为整个 DataSource 的默认值
const dataSource = new DataSource({
    // ...
    relationLoadStrategy: "query",
})
```

<!-- EN -->
You can also control whether eager relations are loaded at all using `loadEagerRelations`:

<!-- ZH -->
你还可以用 `loadEagerRelations` 控制是否加载急加载关系：

<!-- EN -->
```typescript
// disable eager relation loading entirely
const questions = await questionRepository.find({
    loadEagerRelations: false,
})

// load explicit relations only, suppress nested eager relations
const questions = await questionRepository.find({
    relations: { categories: true },
    loadEagerRelations: false,
})
```

<!-- ZH -->
```typescript
// 完全禁用急加载关系
const questions = await questionRepository.find({
    loadEagerRelations: false,
})

// 只加载显式指定的关系，抑制嵌套的急加载关系
const questions = await questionRepository.find({
    relations: { categories: true },
    loadEagerRelations: false,
})
```

<!-- EN -->
## Lazy relations

<!-- ZH -->
## 懒加载关系

<!-- EN -->
Entities in lazy relations are loaded once you access them. Such relations must have `Promise` as type - you store your value in a promise, and when you load them a promise is returned as well. Example:

<!-- ZH -->
懒加载关系中的实体只有在你访问它们时才会被加载。这类关系的类型必须是 `Promise`——你把值存在一个 promise 中，加载它们时返回的也是一个 promise。示例：

<!-- 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: Promise<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: Promise<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)
    @JoinTable()
    categories: Promise<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)
    @JoinTable()
    categories: Promise<Category[]>
}
```

<!-- EN -->
`categories` is a Promise. It means it is lazy and it can store only a promise with a value inside. Example how to save such relation:

<!-- ZH -->
`categories` 是一个 Promise。这意味着它是懒加载的，它内部只能存放一个带值的 promise。保存这种关系的示例：

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

const category2 = new Category()
category2.name = "zoo"
await dataSource.manager.save(category2)

const question = new Question()
question.categories = Promise.resolve([category1, category2])
await dataSource.manager.save(question)
```

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

const category2 = new Category()
category2.name = "zoo"
await dataSource.manager.save(category2)

const question = new Question()
question.categories = Promise.resolve([category1, category2])
await dataSource.manager.save(question)
```

<!-- EN -->
Example how to load objects inside lazy relations:

<!-- ZH -->
加载懒加载关系中对象的示例：

<!-- EN -->
```typescript
const [question] = await dataSource.getRepository(Question).find()
const categories = await question.categories
// you'll have all question's categories inside "categories" variable now
```

<!-- ZH -->
```typescript
const [question] = await dataSource.getRepository(Question).find()
const categories = await question.categories
// 现在 "categories" 变量中就是该 question 的所有分类
```

<!-- EN -->
Note: if you come from other languages (Java, PHP, etc.) and are used to using lazy relations everywhere - be careful. Those languages aren't asynchronous, and lazy loading is achieved in a different way, without the use of promises. In JavaScript and Node.JS, you have to use promises if you want to have lazy-loaded relations. This is a non-standard technique and considered experimental in TypeORM.

<!-- ZH -->
注意：如果你来自其他语言（Java、PHP 等），并且习惯到处使用懒加载关系——请务必小心。那些语言不是异步的，懒加载是通过另一种方式实现的，并不使用 promise。在 JavaScript 和 Node.JS 中，如果你想拥有懒加载关系，就必须使用 promise。这是一种非标准技术，在 TypeORM 中被视为实验性特性。
