---
title: wrap() 辅助函数
sidebar_label: wrap() 辅助函数
---

来源：https://mikro-orm.io/docs/wrap-helper

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

`wrap()` 辅助函数让你能够访问一些操作实体的实用方法。它返回一个 `WrappedEntity` 实例，暴露出用于检查实体状态、加载关联、序列化以及更新值的方法。

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

const book = await em.findOne(Book, 1);

// 检查实体是否已初始化
wrap(book).isInitialized();

// 加载一个关联
await wrap(book.author).init();

// 更新实体值
wrap(book).assign({ title: 'New Title' });

// 序列化为普通对象
const dto = wrap(book).toObject();
```

<a id="wrap-vs-baseentity"></a>
## `wrap()` 与 `BaseEntity`

访问这些辅助方法有两种方式：

**1. 使用 `wrap()` 辅助函数**——保持实体类干净：

<Tabs
groupId="entity-def"
defaultValue="define-entity-class"
values={[
{label: 'defineEntity + class', value: 'define-entity-class'},
{label: 'defineEntity', value: 'define-entity'},
{label: 'reflect-metadata', value: 'reflect-metadata'},
{label: 'ts-morph', value: 'ts-morph'},
]
}
>
  <TabItem value="define-entity-class">

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

const BookSchema = defineEntity({
  name: 'Book',
  properties: {
    id: p.integer().primary(),
    title: p.string(),
  },
});

export class Book extends BookSchema.class {}
BookSchema.setClass(Book);
```

  </TabItem>

<TabItem value="define-entity">

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

export const Book = defineEntity({
  name: 'Book',
  properties: {
    id: p.integer().primary(),
    title: p.string(),
  },
});
```

```ts
// 通过 wrap() 访问辅助方法
wrap(book).assign({ title: 'New Title' });
```

</TabItem>
<TabItem value="reflect-metadata">

```ts title="./entities/Book.ts"
import { Entity, PrimaryKey, Property } from '@mikro-orm/decorators/legacy';

@Entity()
export class Book {

  @PrimaryKey()
  id!: number;

  @Property()
  title!: string;

}
```

```ts
// 通过 wrap() 访问辅助方法
wrap(book).assign({ title: 'New Title' });
```

</TabItem>
<TabItem value="ts-morph">

```ts title="./entities/Book.ts"
import { Entity, PrimaryKey, Property } from '@mikro-orm/decorators/legacy';

@Entity()
export class Book {

  @PrimaryKey()
  id!: number;

  @Property()
  title!: string;

}
```

```ts
// 通过 wrap() 访问辅助方法
wrap(book).assign({ title: 'New Title' });
```

</TabItem>
</Tabs>

**2. 继承 `BaseEntity`**——方法可直接在实体上使用：

<Tabs
groupId="entity-def"
defaultValue="define-entity-class"
values={[
{label: 'defineEntity + class', value: 'define-entity-class'},
{label: 'defineEntity', value: 'define-entity'},
{label: 'reflect-metadata', value: 'reflect-metadata'},
{label: 'ts-morph', value: 'ts-morph'},
]
}
>
  <TabItem value="define-entity-class">

```ts title="./entities/Book.ts"
import { defineEntity, p, BaseEntity } from '@mikro-orm/core';

const BookSchema = defineEntity({
  name: 'Book',
  extends: BaseEntity,
  properties: {
    id: p.integer().primary(),
    title: p.string(),
  },
});

export class Book extends BookSchema.class {}
BookSchema.setClass(Book);
```

  </TabItem>

<TabItem value="define-entity">

```ts title="./entities/Book.ts"
import { defineEntity, p, BaseEntity } from '@mikro-orm/core';

export const Book = defineEntity({
  name: 'Book',
  extends: BaseEntity,
  properties: {
    id: p.integer().primary(),
    title: p.string(),
  },
});
```

```ts
// 直接访问辅助方法
book.assign({ title: 'New Title' });
```

</TabItem>
<TabItem value="reflect-metadata">

```ts title="./entities/Book.ts"
import { BaseEntity } from '@mikro-orm/core';
import { Entity, PrimaryKey, Property } from '@mikro-orm/decorators/legacy';

@Entity()
export class Book extends BaseEntity {

  @PrimaryKey()
  id!: number;

  @Property()
  title!: string;

}
```

```ts
// 直接访问辅助方法
book.assign({ title: 'New Title' });
```

</TabItem>
<TabItem value="ts-morph">

```ts title="./entities/Book.ts"
import { BaseEntity } from '@mikro-orm/core';
import { Entity, PrimaryKey, Property } from '@mikro-orm/decorators/legacy';

@Entity()
export class Book extends BaseEntity {

  @PrimaryKey()
  id!: number;

  @Property()
  title!: string;

}
```

```ts
// 直接访问辅助方法
book.assign({ title: 'New Title' });
```

</TabItem>
</Tabs>

根据你的偏好来选择：是想保持实体接口干净（`wrap()`），还是更看重直接调用方法的便利（`BaseEntity`）。

<a id="available-methods"></a>
## 可用方法

<a id="state-methods"></a>
### 状态方法

| 方法 | 说明 |
|--------|-------------|
| `isInitialized()` | 如果实体已完全加载（而不只是一个引用），返回 `true` |
| `isManaged()` | 如果实体被某个 EntityManager 追踪，返回 `true` |
| `populated(flag?)` | 把实体标记为已填充（或未填充） |

```ts
const author = em.getReference(Author, 1);
wrap(author).isInitialized(); // false——只是一个引用

await wrap(author).init();
wrap(author).isInitialized(); // true——现在已加载
```

<a id="loading-methods"></a>
### 加载方法

| 方法 | 说明 |
|--------|-------------|
| `init(populated?, populate?, lockMode?)` | 从数据库加载实体 |
| `populate(populate, options?)` | 加载指定的关联 |

```ts
// 加载未初始化的引用
const author = em.getReference(Author, 1);
await wrap(author).init();

// 加载特定关联
const book = await em.findOne(Book, 1);
await wrap(book).populate(['author', 'tags']);
```

<a id="serialization-methods"></a>
### 序列化方法

| 方法 | 说明 |
|--------|-------------|
| `toObject(ignoreFields?)` | 把实体转换为普通对象 |
| `toJSON()` | 与 `toObject()` 相同，供 `JSON.stringify()` 使用 |
| `toPOJO()` | 与 `toObject()` 相同 |
| `serialize(options?)` | 转换为普通对象，提供更多控制 |
| `setSerializationContext(options?)` | 为后续序列化设置序列化上下文 |

详细的序列化选项参见[序列化](./50-serializing.md)。

```ts
const book = await em.findOne(Book, 1, { populate: ['author'] });

// 基础序列化
const dto = wrap(book).toObject();

// 带选项
const dto2 = wrap(book).serialize({
  populate: ['author'],
  exclude: ['createdAt'],
});
```

<a id="reference-methods"></a>
### 引用方法

| 方法 | 说明 |
|--------|-------------|
| `toReference()` | 把实体包装进 `Reference` 包装器 |

```ts
const author = await em.findOne(Author, 1);
book.author = wrap(author).toReference();
```

<a id="schema-methods"></a>
### Schema 方法

| 方法 | 说明 |
|--------|-------------|
| `getSchema()` | 返回实体的 schema 名称 |
| `setSchema(schema?)` | 设置实体的 schema 名称 |

<a id="accessing-internal-properties"></a>
### 访问内部属性

要访问 `__meta` 或 `__em` 这类内部属性，请把 `true` 作为第二个参数传入：

```ts
// 仅公开 API
wrap(author);

// 包含内部属性
wrap(author, true).__meta;
wrap(author, true).__em;
```

<a id="updating-entities-with-assign"></a>
## 用 `assign()` 更新实体

`assign()` 方法是最常用的辅助方法之一。它从普通对象更新实体的值，并自动处理关联——把 ID 转换成引用。

<a id="basic-usage"></a>
### 基础用法

不使用 `assign()` 时，更新关联需要手动创建引用：

```ts
const book = await em.findOne(Book, 1);
book.title = 'New Title';
book.author = em.getReference(Author, authorId);
```

使用 `assign()` 时，你可以直接传入包含关联 ID 的普通数据：

```ts
wrap(book).assign({
  title: 'New Title',
  author: authorId, // 会被自动转换成引用
});
```

这在处理用户输入或 API 载荷时尤其有用：

```ts
// Express 路由处理器
app.patch('/books/:id', async (req, res) => {
  const book = await em.findOneOrFail(Book, req.params.id);
  wrap(book).assign(req.body);
  await em.flush();
  res.json(book);
});
```

<a id="assigning-to-unmanaged-entities"></a>
### 给未受管的实体赋值

对于尚未被 EntityManager 接管的实体，请在选项中传入 `em`：

```ts
const book = new Book();
wrap(book).assign({
  title: 'New Book',
  author: authorId,
}, { em });
```

<a id="merging-object-properties"></a>
### 合并对象属性

默认情况下，`assign()` 会替换对象属性（与 `Object.assign()` 一样）。通过 `mergeObjectProperties` 启用深度合并：

```ts
book.meta = { foo: 1, bar: 2 };

// 不合并——替换整个对象
wrap(book).assign({ meta: { foo: 3 } });
console.log(book.meta); // { foo: 3 }

// 合并——深度合并
wrap(book).assign({ meta: { foo: 3 } }, { mergeObjectProperties: true });
console.log(book.meta); // { foo: 3, bar: 2 }
```

可嵌入属性默认会被合并。可以通过 `mergeEmbeddedProperties: false` 关闭。

<a id="updating-nested-relations"></a>
### 更新嵌套关联

要更新嵌套实体，请在数据中包含它的主键，**并且**确保它已在当前上下文中加载：

```ts
const book = await em.findOneOrFail(Book, 1, { populate: ['author'] });

// 更新已有的 author
wrap(book).assign({
  author: {
    id: book.author.id,
    name: 'Updated Name',
  },
});
```

如果没有主键，嵌套对象会被视为新实体（触发 `INSERT`）：

```ts
// 会创建一个新的 author
wrap(book).assign({
  author: {
    name: 'New Author',
  },
});
```

使用 `updateByPrimaryKey: false` 可以在不提供主键的情况下更新已有关联：

```ts
wrap(book).assign({
  author: {
    name: 'Updated Name',
  },
}, { updateByPrimaryKey: false });
```

<a id="updating-collections"></a>
### 更新集合

传入数组会替换集合元素，传入单个元素则会追加：

```ts
// 替换所有地址
wrap(user).assign({ addresses: [new Address(...), new Address(...)] });

// 追加到已有地址
wrap(user).assign({ addresses: new Address(...) });
```

<a id="using-class-based-dtos"></a>
### 使用基于类的 DTO

当使用 `class-validator` 这类校验库时，请继承 `PlainObject`，让 MikroORM 把你的 DTO 当作普通对象处理：

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

class UpdateBookDTO extends PlainObject {

  @IsString()
  title!: string;

  @IsNumber()
  authorId!: number;

}

// dto 是 UpdateBookDTO 的实例
wrap(book).assign(dto);
```

<a id="assign-options"></a>
### `assign()` 选项

| 选项 | 默认值 | 说明 |
|--------|---------|-------------|
| `updateNestedEntities` | `true` | 处理嵌套的关联对象 |
| `updateByPrimaryKey` | `true` | 更新已有关联时要求提供主键 |
| `mergeObjectProperties` | `false` | 深度合并 JSON／对象属性 |
| `mergeEmbeddedProperties` | `true` | 深度合并可嵌入属性 |
| `onlyProperties` | `false` | 忽略载荷中未知的属性 |
| `onlyOwnProperties` | `false` | 跳过反向关联，把其他关联转为外键 |
| `convertCustomTypes` | `false` | 允许自定义类型使用原始数据库值 |
| `ignoreUndefined` | `false` | 跳过 `undefined` 属性 |
| `merge` | `false` | 对新关联使用 `em.merge()` 而非 `em.create()` |
| `schema` | （推断） | 用于查找关联实体的 schema |
| `em` | （推断） | EntityManager 实例（未受管实体必须提供） |

<a id="global-configuration"></a>
### 全局配置

在 ORM 配置中配置 `assign()` 的默认行为：

```ts
await MikroORM.init({
  assign: {
    updateNestedEntities: true,
    updateByPrimaryKey: true,
    mergeObjectProperties: false,
    mergeEmbeddedProperties: true,
  },
});
```
