---
title: 关联加载策略
sidebar_label: 加载策略
---

来源：https://mikro-orm.io/docs/loading-strategies

MikroORM 支持三种加载策略：

- `select-in`：为每个关联使用独立查询——如果你填充两个关联，就会得到三条查询，一条用于根实体，另外两条分别用于每个被填充的关联。
- `joined`：使用单条查询，改为通过连接（join）来获取关联。
- `balanced`：对 `to-one` 关联使用连接，对 `to-many` 关联使用 `select-in`。

> `joined` 策略**仅在 SQL 驱动中受支持**。

> 自 v7 起，`balanced` 策略是 **SQL 驱动的默认值**。

<a id="configuring-the-strategy"></a>
## 配置策略

加载策略既可以在映射时指定，也可以在加载实体时指定，还可以在 ORM 配置中全局指定。

给定下面这些实体：

```ts
import { Collection } from '@mikro-orm/core';
import { Entity, OneToMany, ManyToOne, PrimaryKey } from '@mikro-orm/decorators/legacy';

@Entity()
export class Author {

  @PrimaryKey()
  id!: number;

  @OneToMany(() => Book, b => b.author)
  books = new Collection<Book>(this);

}

@Entity()
export class Book {

  @PrimaryKey()
  id!: number;

  @ManyToOne()
  author: Author;

  @ManyToOne(() => Book, { nullable: true })
  inspiredBy?: Book;

}
```

使用默认的 `balanced` 策略时，会发出两条查询：一条用于加载 `Author` 实体，另一条用于加载它的 `books`，并连接 `books.inspiredBy` 关联。

```ts
const author = await orm.em.findOne(Author, 1, {
  populate: ['books.inspiredBy'],
});
```

要覆盖该策略，可以使用 `strategy` 选项：

```ts
const author = await orm.em.findOne(Author, 1, {
  populate: ['books.inspiredBy'],
  strategy: 'select-in',
});
```

这会发出三条 SQL 语句：一条用于加载 author，另一条用于加载属于该 author 的所有 book，第三条用于获取 `Book.inspiredBy` 关联。

使用 `joined` 策略时，这个例子会用单条查询加载 `Author` 实体及其 `books` 与 `books.inspiredBy` 关联：

```ts
const author = await orm.em.findOne(Author, 1, {
  populate: ['books.inspiredBy'],
  strategy: 'joined',
});
```

此外，你也可以在实体定义中控制策略。

```ts
import { Collection } from '@mikro-orm/core';
import { Entity, OneToMany } from '@mikro-orm/decorators/legacy';

@Entity()
export class Author {

  // ...

  @OneToMany({
    entity: () => Book,
    mappedBy: b => b.author,
    strategy: 'select-in', // 为该关联强制使用 select-in 策略
  })
  books = new Collection<Book>(this);

}
```

在属性级别定义的策略始终优先生效。

<a id="changing-the-loading-strategy-globally"></a>
## 全局修改加载策略

你可以在 ORM 配置中使用 `loadStrategy` 选项：

```ts
MikroORM.init({
  // ...
  loadStrategy: 'select-in', // 对于 SQL 驱动，'balanced' 是默认值
});
```

该值会作为默认值使用；在属性级别指定加载策略的优先级更高，在 `FindOptions` 中指定同样优先级更高。

<a id="per-relation-populate-overrides"></a>
## 按关联覆盖填充行为

`strategy` 选项作用于所有被填充的关联，而你可以通过 `populateHints` 为个别关联覆盖加载策略或连接类型。其键与 `populate` 选项中使用的点分隔路径相同，并且支持自动补全。

```ts
const author = await orm.em.findOne(Author, 1, {
  populate: ['books.inspiredBy'],
  strategy: 'joined',
  populateHints: {
    'books.inspiredBy': { strategy: 'select-in' },
  },
});
```

这会通过连接加载 books，但对 `inspiredBy` 关联使用一条独立的 `select-in` 查询。

你还可以覆盖连接类型。例如，非空的 `ManyToOne` 关联在 `joined` 策略下默认使用 `inner join`。你可以强制改用 `left join`：

```ts
const books = await orm.em.find(Book, {}, {
  populate: ['author'],
  strategy: 'joined',
  populateHints: {
    author: { joinType: 'left join' },
  },
});
```

`strategy` 与 `joinType` 可以在同一个提示中组合使用，你也可以一次为多个关联提供提示：

```ts
const author = await orm.em.findOne(Author, 1, {
  populate: ['books.inspiredBy', 'favouriteBook'],
  strategy: 'joined',
  populateHints: {
    books: { joinType: 'inner join' },
    'books.inspiredBy': { strategy: 'select-in' },
    favouriteBook: { joinType: 'left join' },
  },
});
```

与任何填充条目都不匹配的路径提示会被静默忽略。

<a id="per-parent-limiting"></a>
### 按父实体限制数量

你可以使用 `populateHints` 中的 `limit` 选项来限制每个父实体加载的条目数量。当某个关联可能包含大量条目（例如每个用户有上千篇帖子）但你每个父实体只需要其中少数几项时，这会非常有用。

```ts
const users = await em.find(User, {}, {
  populate: ['posts'],
  populateHints: {
    posts: { limit: 5, orderBy: { createdAt: 'desc' } },
  },
});
// 每个 user.posts 集合最多包含 5 项（最新的那几项）
```

你也可以使用 `offset` 进行分页：

```ts
const users = await em.find(User, {}, {
  populate: ['posts'],
  populateHints: {
    posts: { limit: 5, offset: 5, orderBy: { createdAt: 'desc' } },
  },
});
```

嵌套填充的每一层都可以应用不同的限制：

```ts
const users = await em.find(User, {}, {
  populate: ['posts.comments'],
  populateHints: {
    posts: { limit: 5, orderBy: { createdAt: 'desc' } },
    'posts.comments': { limit: 3 },
  },
});
```

`populateHints` 中的 `orderBy` 优先于嵌套的 `FindOptions.orderBy`。如果两者都未提供，则使用该关联的默认排序。

带限制加载的集合会被标记为**部分且只读**——你无法向其中添加或移除元素，这可以避免工作单元把未加载的条目误当作被移除的条目。

在底层，SQL 驱动会使用 `ROW_NUMBER() OVER (PARTITION BY ...)` 窗口函数，在单条查询中高效地按父实体限制数量。MongoDB 则使用带 `$group` 与 `$slice` 的聚合管道。

> 一旦设置了 `limit`，加载策略会被自动强制为 `select-in`，因为 `joined` 策略无法在连接中应用按父实体的限制。

这同样适用于 `em.populate()`：

```ts
await em.populate(users, ['posts'], {
  populateHints: {
    posts: { limit: 5, orderBy: { createdAt: 'desc' } },
  },
});
```

<a id="population-where-condition"></a>
## 填充的 `where` 条件

默认情况下，where 条件只作用于根实体。这可以通过 `populateWhere` 选项来控制。它接受 `all`（默认）、`infer`（使用与 `where` 查询相同的条件）之一，或者一个显式的过滤查询。

```ts
await em.find(Author, { ... }, {
  populate: ['books'],
  populateWhere: 'infer', // 默认为 `all`

  // 或者指定自定义查询，它会通过 `join on` 条件来使用
  // populateWhere: { age: { $gte: 18 } },
});
```

> `populateWhere` 也可以全局设置，默认值为 `all`。

<a id="population-order-by-clause"></a>
## 填充的 `order by` 子句

与 `populateWhere` 类似，你也可以控制填充查询所使用的 `order by` 子句。默认行为是与根实体使用相同的排序，你可以通过 `populateOrderBy` 选项添加不同的排序：

```ts
await em.find(Author, { ... }, {
  populate: ['books'],
  populateOrderBy: { books: { publishedAt: 'desc' } },
});
```
