---
title: '第 2 章：关联关系'
---

来源：https://mikro-orm.io/docs/guide/relationships

import BrowserOnly from '@docusaurus/BrowserOnly';
import Playground from '@site/src/playground/Playground';

在本节中，我们会添加更多实体、定义共享的基础属性，并在它们之间建立关联关系。

<a id="created-and-updated-timestamps"></a>
## 创建与更新时间戳

在添加更多实体之前，先稍微重构一下已有的 `User` 实体。我们希望记录实体创建的时间以及最后一次更新的时间。使用 `defineEntity` 时，我们通过属性构建器来添加它们：

```ts title='user.entity.ts'
createdAt: p.datetime().onCreate(() => new Date()),
updatedAt: p.datetime().onCreate(() => new Date()).onUpdate(() => new Date()),
```

如果 ORM 检测到实体被更新，`.onUpdate()` 回调会在 `flush` 操作期间执行。对于创建查询，则使用 `.onCreate()` 来设置初始值。

<a id="base-entity"></a>
## 基础实体

现在假设我们希望应用中的每个实体都带有这些时间戳（以及主键）。使用 `defineEntity` 时，我们可以创建一个供其他实体继承的基础实体。把下面内容放进 `src/modules/common/base.entity.ts`：

```ts title='base.entity.ts'
import { defineEntity, p } from '@mikro-orm/core';

export const BaseSchema = defineEntity({
  name: 'BaseEntity',
  abstract: true,
  properties: {
    id: p.integer().primary(),
    createdAt: p.datetime().onCreate(() => new Date()),
    updatedAt: p.datetime().onCreate(() => new Date()).onUpdate(() => new Date()),
  },
});
```

这是一个抽象实体（它不会有自己的表）。其他实体可以通过 `extends` 选项继承它：

> 你会注意到导入语句带有 `.js` 扩展名——这在 ESM 项目中是必需的。如果你的项目面向 CommonJS，可以去掉它。

```ts title='user.entity.ts'
import { defineEntity, type InferEntity, p } from '@mikro-orm/core';
import { BaseSchema } from '../common/base.entity.js';

export const UserSchema = defineEntity({
  name: 'User',
  extends: BaseSchema,
  properties: {
    fullName: p.string(),
    email: p.string(),
    password: p.string(),
    bio: p.text().default(''),
  },
});

export type IUser = InferEntity<typeof UserSchema>;
```

<a id="more-entities"></a>
## 更多实体

是时候添加 `Article` 实体了。它会有 4 个字符串属性和 1 个关联关系——一个指向 `User` 实体的 ManyToOne 关联。如你所料，它会放在 `src/modules/article/article.entity.ts` 文件中。

```ts title='article.entity.ts'
import { defineEntity, InferEntity, p } from '@mikro-orm/core';
import { BaseSchema } from '../common/base.entity.js';
import { UserSchema } from '../user/user.entity.js';

export const ArticleSchema = defineEntity({
  name: 'Article',
  extends: BaseSchema,
  properties: {
    slug: p.string().unique(),
    title: p.string().index(),
    description: p.string().length(1000),
    text: p.text().lazy(),
    author: () => p.manyToOne(UserSchema),
  },
});

export type IArticle = InferEntity<typeof ArticleSchema>;
```

我们来拆解一下，这里有一些之前没见过的新东西：

- `slug` 属性被标记为 `.unique()`，这会在该列上生成唯一约束
- `title` 属性被标记为 `.index()`
- `description` 属性带有 `.length(1000)`，在大多数 SQL 驱动下该列会变成 `varchar(1000)`
- `text` 属性使用 `.text()` 表示文本类型，并被标记为 `.lazy()`，意味着它不会被自动 select
- `author` 属性是我们的第一个关联关系，用 `p.manyToOne(UserSchema)` 定义

注意，对于 `author: () => p.manyToOne(UserSchema)` 这类关联，我们使用了箭头函数。箭头函数包装是必需的，用来处理实体之间的循环引用。

> 你可以更新 `mikro-orm.config.ts`，把新的 `Article` 实体加入 `entities` 数组，但这并非严格必需。只要该实体出现在某个已被发现的实体的关联关系中，它就会被自动发现。

<a id="types-of-relations"></a>
## 关联关系的类型

MikroORM 中有 4 种实体关联关系：

- ManyToOne：当前实体的多个实例指向被引用实体的一个实例。
- OneToMany：当前实体的一个实例拥有被引用实体的多个实例（引用）。
- OneToOne：当前实体的一个实例指向被引用实体的一个实例。
- ManyToMany：当前实体的多个实例指向被引用实体的多个实例。

关联关系可以是单向的，也可以是双向的。单向关联只在一方定义（拥有方）。双向关联在两方都定义，其中一方是拥有方（引用存储在这一侧），用 `inversedBy` 属性指向反向方。在反向方，你用 `mappedBy` 属性指回拥有方。

> 建模双向关联时，你也可以省略 `inversedBy` 属性——只在反向方定义 `mappedBy` 就足够了，它会被自动接线。

关于每种类型的更多细节与示例，请查阅文档中的[实体关联建模](./19-relationships.md)一节。

<a id="working-with-relations"></a>
## 使用关联关系

回到 `server.ts` 文件，用新的 `Article` 实体做些尝试，主要是它的 `author` 关联。

<a id="creating-entity-graph"></a>
### 创建实体图

我们一直在用 [`em.create()`](https://mikro-orm.io/api/core/class/EntityManager#create) 创建实体实例。这个方法允许你创建深层的实体图，把关联关系中的外键映射为正确类型的实体引用。它还会对创建出的实体调用 [`em.persist()`](https://mikro-orm.io/api/core/class/EntityManager#persist)（除非通过 `persistOnCreate` 选项禁用）。

> 你可以把 `server.ts` 文件的大部分内容清空，只保留 ORM 初始化那一段——直到第一个 `User` 实体被 flush 为止——再加上末尾的 `orm.close()` 调用。接下来我们不会再用到这些代码，它只是供你试验的游乐场。

```ts title='server.ts'
// 先 fork，以获得独立的上下文
const em = orm.em.fork();

// 创建新的 user 实体实例
const user = em.create(UserSchema, {
  email: 'foo@bar.com',
  fullName: 'Foo Bar',
  password: '123456',
});

// em.create 会自动持久化，所以只需 flush
await em.flush();

// 清空上下文，模拟一次全新的请求
em.clear();

// 创建 article 实例
const article = em.create(ArticleSchema, {
  slug: 'foo',
  title: 'Foo',
  text: 'Lorem impsum dolor sit amet',
  description: 'Foo is bar',
  author: user.id,
});

// `em.create` 会自动调用 `em.persist`，所以 flush 就够了
await em.flush();
console.log(article);
```

:::info `em.clear()`

如果你仔细看了这段代码，大概已经发现了那个陌生的 [`em.clear()`](https://mikro-orm.io/api/core/class/EntityManager#clear) 调用。它做了什么？它会清空该 [`EntityManager`](https://mikro-orm.io/api/core/class/EntityManager) 的上下文，也就是说它会分离（detach）所有被它接管的实体。这会让 [`EntityManager`](https://mikro-orm.io/api/core/class/EntityManager) 回到与通过 [`em.fork()`](https://mikro-orm.io/api/core/class/EntityManager#fork) 创建全新 fork 时相同的状态。你在应用中通常不需要这么做，但它在单元测试中非常方便，可以模拟新请求的到来。如果你愿意，也可以显式使用 fork。

:::

<a id="type-inference-with-defineentity"></a>
### `defineEntity` 的类型推断

`defineEntity` 的好处之一是可选属性会被自动推断！当你使用 `.default()`、`.onCreate()` 或 `.onUpdate()` 时，该属性在 TypeScript 中会自动被标记为可选。

在我们的 `BaseEntity` 中，三个属性都是可选的：
- `id` 是单个数值主键，因此会假定为自增
- `createdAt` 使用 `.onCreate()`
- `updatedAt` 使用 `.onCreate()` 与 `.onUpdate()`

所以 TypeScript 已经知道它们在 `em.create()` 调用中是可选的——无需任何额外配置！

运行 `npm start`，你会看到 `Article` 实体被持久化并输出到控制台：

```
[query] begin
[query] insert into `article` (`author_id`, `created_at`, `description`, `slug`, `text`, `title`, `updated_at`) values (1, 1662908804371, 'Foo is bar', 'foo', 'Lorem impsum...', 'Foo', 1662908804371) [took 0 ms]
[query] commit
Article {
  id: 1,
  createdAt: 2022-09-11T15:06:44.371Z,
  updatedAt: 2022-09-11T15:06:44.371Z,
  slug: 'foo',
  title: 'Foo',
  description: 'Foo is bar',
  text: 'Lorem impsum...',
  author: (User) { id: 1 }
}
```

还记得之前讨论过的实体引用与加载状态吗？这里就能看到它们在起作用：`Article.author` 是一个只有主键的实体引用。它会被自动打印为 `(User)`，这样你就能轻松判断任何实体的加载状态；但事实上它就是同一个 `User` 实体实例：

```ts
console.log('it really is a User', article.author instanceof User); // true
console.log('but not initialized', wrap(article.author).isInitialized()); // false
```

<a id="using-oncreate-for-computed-properties"></a>
### 用 `onCreate` 处理计算属性

每篇 `Article` 都可以通过唯一的 slug 来标识——一个可用于查找文章的 URL 片段。目前它只是一个普通的字符串属性，但我们可以做得更好：它的值应该始终与文章标题绑定。为简单起见，我们使用下面这个函数：

```ts
function convertToSlug(text: string) {
  return text.toLowerCase()
             .replace(/[^\w ]+/g, '')
             .replace(/ +/g, '-');
}
```

我们希望文章创建之后 URL 保持不变，所以用 `.onCreate()` 来生成 slug。同理，我们也可以从正文生成描述：

```ts title='article.entity.ts'
import { defineEntity, InferEntity, p } from '@mikro-orm/core';
import { BaseSchema } from '../common/base.entity.js';
import { UserSchema } from '../user/user.entity.js';

function convertToSlug(text: string) {
  return text.toLowerCase()
             .replace(/[^\w ]+/g, '')
             .replace(/ +/g, '-');
}

export const ArticleSchema = defineEntity({
  name: 'Article',
  extends: BaseSchema,
  properties: {
    slug: p.string().unique().onCreate(article => convertToSlug(article.title)),
    title: p.string().index(),
    description: p.string().length(1000).onCreate(article => article.text.substring(0, 999) + '…'),
    text: p.text().lazy(),
    author: () => p.manyToOne(UserSchema),
  },
});

export type IArticle = InferEntity<typeof ArticleSchema>;
```

有了 `.onCreate()`，`slug` 与 `description` 属性在 [`em.create()`](https://mikro-orm.io/api/core/class/EntityManager#create) 中会自动变为可选——无需额外的类型配置！

```ts
const article = em.create(ArticleSchema, {
  title: 'Foo is Bar',
  text: 'Lorem impsum dolor sit amet',
  author: user.id,
});
console.log(article);
```

运行 `npm start`，你可以看到 `slug` 与 `description` 被填充了生成的值：

```
Article {
  id: 1,
  createdAt: 2022-09-11T16:08:16.489Z,
  updatedAt: 2022-09-11T16:08:16.489Z,
  slug: 'foo-is-bar',
  title: 'Foo is Bar',
  description: 'Lorem impsum dolor sit amet…',
  text: 'Lorem impsum dolor sit amet',
  author: (User) { id: '1' }
}
```

<a id="populating-relationships"></a>
## 填充关联关系

如果我们想连同 `author` 关联一起获取 `Article` 呢？可以使用 `populate` 提示：

```ts title='server.ts'
// 清空上下文，模拟一次全新的请求
em.clear();

// 按 id 查找文章并填充其 author
const articleWithAuthor = await em.findOne(ArticleSchema, article.id, { populate: ['author'] });
console.log(articleWithAuthor);
```

照常运行 `npm start`：

```
Article {
  id: 1,
  createdAt: 2022-09-11T16:57:57.941Z,
  updatedAt: 2022-09-11T16:57:57.941Z,
  slug: 'foo-is-bar',
  title: 'Foo is Bar',
  description: 'Lorem impsum dolor sit amet…',
  text: undefined,
  author: User {
    id: 1,
    fullName: 'Foo Bar',
    email: 'foo@bar.com',
    password: '123456',
    bio: ''
  }
}
```

<a id="lazy-scalar-properties"></a>
### 惰性标量属性

你可以看到 `text` 属性是 `undefined`——这是因为我们把它标记为 `lazy`，因此它的值不会被自动 select。如果把 `text` 加入 populate 提示，就能拿到它的值：

```ts title='server.ts'
const articleWithAuthor = await em.findOne(ArticleSchema, article.id, {
  populate: ['author', 'text'],
});
```

如果实体已经加载，也可以使用 `em.populate()`：

```ts title='server.ts'
const articleWithAuthor = await em.findOne(ArticleSchema, article.id, {
  populate: ['author'],
});
await em.populate(articleWithAuthor!, ['text']);
```

<a id="loading-strategies"></a>
### 加载策略

你可以看到 `Article` 与它的 `author` 关联是在一条 join 查询中一起加载的。这得益于 MikroORM v7 的默认加载策略 `LoadStrategy.BALANCED`。该策略对「对一」关联（如 ManyToOne 与 OneToOne）使用 SQL join，对「对多」关联（如 OneToMany 与 ManyToMany）使用独立查询。这种方式避免了加载集合时由笛卡尔积引起的性能问题——如果你 join 多个「对多」关联，结果集会因为行数相乘而急剧膨胀。

由于 `Article.author` 是 ManyToOne（对一）关联，balanced 策略会使用 join。如果需要，你也可以显式指定其他策略：

- `LoadStrategy.JOINED` - 对所有关联始终使用 SQL join
- `LoadStrategy.SELECT_IN` - 对所有关联始终使用独立查询

```ts title='server.ts'
const articleWithAuthor = await em.findOne(ArticleSchema, article.id, {
  populate: ['author', 'text'],
  strategy: LoadStrategy.SELECT_IN, // 改用独立查询
});
```

这会产生两条独立查询，而不是一条 join 查询。

> balanced 策略为大多数场景提供了不错的默认值。如果你想全局修改加载策略，请使用 ORM 配置中的 `loadStrategy` 选项。

<a id="serialization"></a>
### 序列化

那密码呢？看到日志里带有已填充 `author` 的 `Article` 实体，有件事你必须修：你能看到用户的密码，而且是明文！你需要通过添加 `.hidden()` 序列化标记来确保它永远不会泄露到 API 响应中。此外，还可以像对待 `Article.text` 那样把它标记为 `.lazy()`，因为你很少会想要 select 它。

```ts title='user.entity.ts'
import { defineEntity, type InferEntity, p } from '@mikro-orm/core';
import { BaseSchema } from '../common/base.entity.js';

export const UserSchema = defineEntity({
  name: 'User',
  extends: BaseSchema,
  properties: {
    fullName: p.string(),
    email: p.string(),
    password: p.string().hidden().lazy(),
    bio: p.text().default(''),
  },
});

export type IUser = InferEntity<typeof UserSchema>;
```

再次运行 `npm start` 后，当你加载 `Article.author` 时，密码不再被 select（得益于 `.lazy()`），也不会被序列化进 API 响应（得益于 `.hidden()`）：

```
Article {
  ...
  author: User {
    id: 1,
    fullName: 'Foo Bar',
    email: 'foo@bar.com',
    bio: ''
  }
}
```

密码在数据库中仍然是明文存储的——别担心，你很快就会通过生命周期钩子用 `argon2` 来修掉这一点！

<a id="collections-onetomany-and-manytomany"></a>
## 集合：OneToMany 与 ManyToMany

我们已经有了 `Article.author` 属性，它定义了 `Article` 与 `User` 实体之间关联关系的拥有方。现在来定义反向方——对于 ManyToOne 关联，反向方是 OneToMany 类型，由一个 `Article` 实体的 `Collection` 表示。使用 `defineEntity` 时，你会用到 `p.oneToMany()`：

```ts title='user.entity.ts'
export const UserSchema = defineEntity({
  name: 'User',
  extends: BaseSchema,
  properties: {
    fullName: p.string(),
    email: p.string(),
    password: p.string().hidden().lazy(),
    bio: p.text().default(''),
    articles: () => p.oneToMany(ArticleSchema).mappedBy('author'),
  },
});

export type IUser = InferEntity<typeof UserSchema>;
```

MikroORM 通过 `Collection` 类来表示这类关联。在深入了解它的含义之前，我们先给 `Article` 模块再加一个实体，以便同时测试 ManyToMany 关联。它会是一个 `Tag` 实体，这样你就可以根据动态定义的标签给文章分类。

> 从语义上说 `Tag` 实体属于 `Article` 模块，所以我们就把它放在那里，即 `src/modules/article/tag.entity.ts` 文件。别忘了把它加入配置中的 `entities` 数组！

```ts title='tag.entity.ts'
import { defineEntity, InferEntity, p } from '@mikro-orm/core';
import { BaseSchema } from '../common/base.entity.js';
import { ArticleSchema } from './article.entity.js';

export const TagSchema = defineEntity({
  name: 'Tag',
  extends: BaseSchema,
  properties: {
    name: p.string().length(20),
    articles: () => p.manyToMany(ArticleSchema).mappedBy('tags'),
  },
});

export type ITag = InferEntity<typeof TagSchema>;
```

你还需要定义拥有方，也就是 `Article.tags`：

```ts title='article.entity.ts'
export const ArticleSchema = defineEntity({
  name: 'Article',
  extends: BaseSchema,
  properties: {
    slug: p.string().unique().onCreate(article => convertToSlug(article.title)),
    title: p.string().index(),
    description: p.string().length(1000).onCreate(article => article.text.substring(0, 999) + '…'),
    text: p.text().lazy(),
    author: () => p.manyToOne(UserSchema),
    tags: () => p.manyToMany(TagSchema),
  },
});
```

从反向方通过 `mappedBy` 选项指向拥有方（或反过来）就足够了。如果你想从拥有方定义关联，请使用 `inversedBy` 选项。既未定义这两者中任何一个的 ManyToMany 关联，总是会被视为拥有方。

```ts
tags: () => p.manyToMany(TagSchema).inversedBy('articles'),
```

<a id="working-with-collections"></a>
### 使用集合

`Collection` 类实现了[可迭代协议](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol)，因此你可以用 `for of` 循环遍历它。

另一种访问集合元素的方式是使用方括号语法，就像访问数组元素那样。请注意，这种方式不会检查集合是否已初始化，而使用 `getItems()` 方法在这种情况下会抛出错误。

> 注意，`Collection` 的数组式访问只能用于读取已加载的元素，你无法通过这种方式向 `Collection` 添加新元素。

要获取 `Collection` 中存储的所有实体，可以使用 `getItems()` 方法。如果 `Collection` 未初始化，它会抛出异常。如果你想禁用这项校验，可以使用 `getItems(false)`。这会返回由标识映射接管的实体实例。

另外，你也可以使用 `toArray()`，它会把 `Collection` 序列化为一个 DTO 数组。修改这些 DTO 不会对真正的实体实例产生任何影响。

:::tip `em.findOneOrFail()`

到目前为止你用的都是 `em.findOne()`，它在数据库中找不到实体时会返回 `null`。这会导致在 TypeScript 中大量使用非空断言运算符，代码会变得很乱。更好的方案是使用 `em.findOneOrFail()`，它总是返回实体，否则抛出错误——具体来说，是 ORM 提供的 `NotFoundError` 实例。

:::

```ts
// 清空上下文，模拟一次全新的请求
em.clear();

// 填充 User.articles 集合
const user = await em.findOneOrFail(UserSchema, 1, { populate: ['articles'] });
console.log(user);

// 或者你也可以稍后通过 `init()` 方法惰性加载该集合
if (!user.articles.isInitialized()) {
  await user.articles.init();
}

// 若要确保集合已加载（但如果已加载则什么都不做），请使用 `loadItems()` 方法
await user.articles.loadItems();

for (const article of user.articles) {
   console.log(article.title);
   console.log(article.author.fullName); // 得益于标识映射，`article.author` 会被自动关联上
}
```

> `Collection.init()` 总是会查询数据库，而 `Collection.loadItems()` 只在集合尚未初始化时才查询，因此调用 `Collection.loadItems()` 时无需事先检查 `isInitialized()`。

运行后你会得到如下输出：

```
User {
  id: 1,
  createdAt: 2022-09-11T18:18:14.376Z,
  updatedAt: 2022-09-11T18:18:14.376Z,
  fullName: 'Foo Bar',
  email: 'foo@bar.com',
  password: undefined,
  bio: '',
  articles: Collection<Article> {
    '0': Article {
      id: 1,
      createdAt: 2022-09-11T18:18:14.384Z,
      updatedAt: 2022-09-11T18:18:14.384Z,
      slug: 'foo-is-bar',
      title: 'Foo is Bar',
      description: 'Lorem impsum dolor sit amet…',
      text: undefined,
      author: [User],
      tags: [Collection<Tag>]
    },
    initialized: true,
    dirty: false
  }
}
```

现在尝试给第一篇文章添加一些标签：

```ts title='server.ts'
// 创建一些标签并把它们赋给第一篇文章
const [article] = user.articles;
const newTag = em.create(TagSchema, { name: 'new' });
const oldTag = em.create(TagSchema, { name: 'old' });
article.tags.add(newTag, oldTag);
await em.flush();
console.log(article.tags);
```

另外，不妨再试着移除其中一个标签：

```ts title='server.ts'
// 要从集合中移除元素，先用 `init()`、`loadItems()` 或 `em.populate()` 初始化它
await em.populate(article, ['tags']);

// 按引用移除 'old' 标签
article.tags.remove(oldTag);

// 或者通过回调
article.tags.remove(t => t.id === oldTag.id);

await em.flush();
```

更多信息与示例请查阅文档中的[集合](./15-collections.md)一节。

<a id="cascading"></a>
## 级联

在持久化或删除实体时，MikroORM 会自动把操作级联到关联实体上。默认情况下，所有关联都启用了 `Cascade.PERSIST`——这意味着当你持久化一个实体时，它所有已加载的关联实体也会被持久化。这正是为什么带嵌套数据的 `em.create()` 能够「直接工作」。

你可以通过 `.cascade()` 构建器方法控制这一行为：

```ts
import { Cascade } from '@mikro-orm/core';

// 默认：仅级联持久化
tags: () => p.manyToMany(TagSchema),

// 同时级联持久化与删除
tags: () => p.manyToMany(TagSchema).cascade(Cascade.PERSIST, Cascade.REMOVE),

// 级联全部操作（持久化 + 删除）
tags: () => p.manyToMany(TagSchema).cascade(Cascade.ALL),

// 完全禁用级联
tags: () => p.manyToMany(TagSchema).cascade(),
```

`Cascade.REMOVE` 意味着删除父实体时也会删除相关实体。在 ManyToOne 关联上使用它要格外小心，因为被删除的实体可能仍被其他地方引用。

<a id="orphan-removal"></a>
### 孤儿删除

在第 3 章中添加 `Article.comments` 时，我们会使用 `orphanRemoval: true`。这是一种更激进的级联形式：任何从集合中被移除的实体都会从数据库中彻底删除，而不仅仅是把它的外键设为 `null`。

```ts
comments: () => p.oneToMany(CommentSchema).mappedBy('article').orphanRemoval(),
```

当子实体脱离父实体就失去意义时，这很有用——从文章集合中移除的评论应该被删除，而不是作为孤儿留在数据库里。

<a id="propagation"></a>
### 传播

MikroORM 还会自动传播关联赋值。当你设置 `comment.article = article` 时，`article.comments` 集合也会同步更新（反之亦然）。这对所有双向关联都有效，也正是它让标识映射保持一致。

> 传播要生效，必须经过发现阶段（发生在 `MikroORM.init()` 或 `new MikroORM()` 期间）。更多细节参见[传播](./56-propagation.md)文档。

关于级联的更多内容，请阅读文档中的[级联](./49-cascading.md)。

<a id="events-and-life-cycle-hooks"></a>
# 事件与生命周期钩子

是时候改进密码哈希了。我们使用 `argon2` 包，它提供了 `hash` 与 `verify` 函数。两者都是异步的，因此你无法直接使用 `.onCreate()`。取而代之，你需要通过 schema 上的 `addHook()` 方法使用生命周期钩子。

> 别忘了通过 `npm install argon2` 安装 `argon2` 包。

计划如下：

- 通过 `em.create()` 赋值时，密码仍然是明文
- `hashPassword` 函数将通过 `addHook()` 成为一个事件处理器
- 你把它同时注册到 `beforeCreate` 与 `beforeUpdate` 事件上
- 处理器接收 `EventArgs`，其中包含带有计算结果的 `changeSet`
- 你检查 `changeSet.payload.password`，只在密码发生变化时才做哈希

```ts title='user.entity.ts'
import { defineEntity, type EventArgs, p } from '@mikro-orm/core';
import { BaseSchema } from '../common/base.entity.js';
import { ArticleSchema } from '../article/article.entity.js';
import { hash, verify } from 'argon2';

async function hashPassword(args: EventArgs<User>) {
  // 只在密码发生变化时做哈希
  const password = args.changeSet?.payload.password;

  if (typeof password === 'string') {
    args.entity.password = await hash(password);
  }
}

export const UserSchema = defineEntity({
  name: 'User',
  extends: BaseSchema,
  properties: {
    fullName: p.string(),
    email: p.string(),
    password: p.string().hidden().lazy(),
    bio: p.text().default(''),
    articles: () => p.oneToMany(ArticleSchema).mappedBy('author'),
  },
});

// 扩展 schema 自动生成的类，以添加自定义方法
export class User extends UserSchema.class {
  async verifyPassword(password: string) {
    return verify(this.password, password);
  }
}

UserSchema.setClass(User);
UserSchema.addHook('beforeCreate', hashPassword);
UserSchema.addHook('beforeUpdate', hashPassword);
```

注意我们是如何用 `setClass()` 扩展 schema 自动生成的类的。这样就无需在类中重新声明所有属性——它们会自动从 schema 推断出来。`User` 类只添加了 `verifyPassword` 方法。调用 `setClass()` 之后，MikroORM 会对所有实体实例使用自定义的 `User` 类，因此 `em.create(User, {...})` 与 `em.find(User, {})` 都能正常工作。

> 虽然 `defineEntity` 也接受 `hooks` 选项，但请优先使用 `addHook()`。`hooks` 选项会把处理器类型标注为 `EventArgs<any>`，从而丢失类型安全。而使用 `addHook()` 时，处理器类型会从参数推断出来，因此你能对 `args.entity` 与 `args.changeSet` 获得正确的类型检查。

<a id="-checkpoint-2"></a>
## ⛳ 检查点 2

我们新增了 2 个实体：`Article` 与 `Tag`，以及一个供它们继承的 `BaseEntity`。你可以在此找到当前状态的可运行 StackBlitz：

> 这里使用的是内存数据库，是 SQLite 通过特殊数据库名 `:memory:` 提供的特性。

编辑代码并按下 **Run**，即可在完全运行于浏览器（通过 WebAssembly）的真实 SQLite 数据库上执行它：

<BrowserOnly>{() => <Playground project="relationships" />}</BrowserOnly>
