# 懒加载与急加载

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

---

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

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

<!-- EN -->
TypeORM provides two main methods for loading data relations: Lazy Loading and Eager Loading. Each has a different impact on the performance of your application.

<!-- ZH -->
TypeORM 提供了两种加载数据关系的主要方式：懒加载（Lazy Loading）和急加载（Eager Loading）。两者对你应用的性能有不同影响。

<!-- EN -->
## Lazy loading

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

<!-- EN -->
Lazy loading loads the relation data only when needed, reducing database load when all related data isn't always necessary.

<!-- ZH -->
懒加载只在需要时才加载关系数据，当并非总是需要全部关联数据时，它能降低数据库负载。

<!-- EN -->
```typescript
@Entity()
export class User {
    @OneToMany(() => Post, (post) => post.user, { lazy: true })
    posts: Promise<Post[]>
}
```

<!-- ZH -->
```typescript
@Entity()
export class User {
    @OneToMany(() => Post, (post) => post.user, { lazy: true })
    posts: Promise<Post[]>
}
```

<!-- EN -->
When you need to retrieve the data, simply call

<!-- ZH -->
当你需要取回数据时，只需调用

<!-- EN -->
```typescript
const user = await userRepository.findOneBy({ id: userId })
const posts = await user.posts
```

<!-- ZH -->
```typescript
const user = await userRepository.findOneBy({ id: userId })
const posts = await user.posts
```

<!-- EN -->
Advantages:

<!-- ZH -->
优点：

<!-- EN -->
* Resource efficiency: Only loads the necessary data when actually required, reducing query costs and memory usage.
* Ideal for selective data usage: Suitable for scenarios where not all related data is needed.

<!-- ZH -->
* 资源高效：只在真正需要时才加载必要的数据，降低查询成本与内存占用。
* 适合选择性使用数据的场景：适用于并非所有关联数据都需要的场合。

<!-- EN -->
Disadvantages:

<!-- ZH -->
缺点：

<!-- EN -->
* Increased query complexity: Each access to related data triggers an additional query to the database, which may increase latency if not managed properly.
* Difficult to track: Can lead to the n+1 query problem if used carelessly.

<!-- ZH -->
* 查询复杂度上升：每次访问关联数据都会额外触发一次数据库查询，如果管理不当可能增加延迟。
* 难以追踪：使用不慎可能导致 n+1 查询问题。

<!-- EN -->
## Eager Loading

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

<!-- EN -->
Eager loading automatically retrieves all related data when the main query is executed. This can be convenient but may cause performance issues if there are too many complex relations.

<!-- ZH -->
急加载会在主查询执行时自动取回所有关联数据。这很方便，但如果存在过多复杂关系，可能引发性能问题。

<!-- EN -->
```typescript
@Entity()
export class User {
    @OneToMany(() => Post, (post) => post.user, { eager: true })
    posts: Post[]
}
```

<!-- ZH -->
```typescript
@Entity()
export class User {
    @OneToMany(() => Post, (post) => post.user, { eager: true })
    posts: Post[]
}
```

<!-- EN -->
In this case, posts will be loaded as soon as user data is retrieved.

<!-- ZH -->
在这种情况下，一旦取回 user 数据，posts 也会被加载。

<!-- EN -->
Advantages:

<!-- ZH -->
优点：

<!-- EN -->
* Automatically loads related data, making it easier to access relationships without additional queries.
* Avoids the n+1 query problem: Since all data is fetched in a single query, there's no risk of generating unnecessary multiple queries.

<!-- ZH -->
* 自动加载关联数据，让你无需额外查询就能更轻松地访问关系。
* 避免 n+1 查询问题：由于所有数据都在单条查询中取回，不存在产生不必要的多条查询的风险。

<!-- EN -->
Disadvantages:

<!-- ZH -->
缺点：

<!-- EN -->
* Fetching all related data at once may result in large queries, even if not all data is needed.
* Not suitable for scenarios where only a subset of related data is required, as it can lead to inefficient data usage.

<!-- ZH -->
* 一次性取回所有关联数据可能产生很大的查询，即使并非所有数据都被需要。
* 不适合只需要关联数据中一部分的场景，因为它可能导致数据使用低效。

<!-- EN -->
To explore more details and examples of how to configure and use lazy and eager relations, visit the official TypeORM documentation: [Eager and Lazy Relations](https://typeorm.io/docs/relations/eager-and-lazy-relations)

<!-- ZH -->
要深入了解如何配置和使用懒加载与急加载关系的更多细节和示例，请访问 TypeORM 官方文档：[急加载与懒加载关系](https://typeorm.io/docs/relations/eager-and-lazy-relations)
