wrap() 辅助函数
wrap() 辅助函数让你能够访问一些操作实体的实用方法。它返回一个 WrappedEntity 实例,暴露出用于检查实体状态、加载关联、序列化以及更新值的方法。
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();wrap() 与 BaseEntity
访问这些辅助方法有两种方式:
1. 使用 wrap() 辅助函数——保持实体类干净:
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);import { defineEntity, p } from '@mikro-orm/core';
export const Book = defineEntity({
name: 'Book',
properties: {
id: p.integer().primary(),
title: p.string(),
},
});// 通过 wrap() 访问辅助方法
wrap(book).assign({ title: 'New Title' });import { Entity, PrimaryKey, Property } from '@mikro-orm/decorators/legacy';
@Entity()
export class Book {
@PrimaryKey()
id!: number;
@Property()
title!: string;
}// 通过 wrap() 访问辅助方法
wrap(book).assign({ title: 'New Title' });import { Entity, PrimaryKey, Property } from '@mikro-orm/decorators/legacy';
@Entity()
export class Book {
@PrimaryKey()
id!: number;
@Property()
title!: string;
}// 通过 wrap() 访问辅助方法
wrap(book).assign({ title: 'New Title' });2. 继承 BaseEntity——方法可直接在实体上使用:
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);import { defineEntity, p, BaseEntity } from '@mikro-orm/core';
export const Book = defineEntity({
name: 'Book',
extends: BaseEntity,
properties: {
id: p.integer().primary(),
title: p.string(),
},
});// 直接访问辅助方法
book.assign({ title: 'New Title' });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;
}// 直接访问辅助方法
book.assign({ title: 'New Title' });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;
}// 直接访问辅助方法
book.assign({ title: 'New Title' });根据你的偏好来选择:是想保持实体接口干净(wrap()),还是更看重直接调用方法的便利(BaseEntity)。
可用方法
状态方法
| 方法 | 说明 |
|---|---|
isInitialized() | 如果实体已完全加载(而不只是一个引用),返回 true |
isManaged() | 如果实体被某个 EntityManager 追踪,返回 true |
populated(flag?) | 把实体标记为已填充(或未填充) |
const author = em.getReference(Author, 1);
wrap(author).isInitialized(); // false——只是一个引用
await wrap(author).init();
wrap(author).isInitialized(); // true——现在已加载加载方法
| 方法 | 说明 |
|---|---|
init(populated?, populate?, lockMode?) | 从数据库加载实体 |
populate(populate, options?) | 加载指定的关联 |
// 加载未初始化的引用
const author = em.getReference(Author, 1);
await wrap(author).init();
// 加载特定关联
const book = await em.findOne(Book, 1);
await wrap(book).populate(['author', 'tags']);序列化方法
| 方法 | 说明 |
|---|---|
toObject(ignoreFields?) | 把实体转换为普通对象 |
toJSON() | 与 toObject() 相同,供 JSON.stringify() 使用 |
toPOJO() | 与 toObject() 相同 |
serialize(options?) | 转换为普通对象,提供更多控制 |
setSerializationContext(options?) | 为后续序列化设置序列化上下文 |
详细的序列化选项参见序列化。
const book = await em.findOne(Book, 1, { populate: ['author'] });
// 基础序列化
const dto = wrap(book).toObject();
// 带选项
const dto2 = wrap(book).serialize({
populate: ['author'],
exclude: ['createdAt'],
});引用方法
| 方法 | 说明 |
|---|---|
toReference() | 把实体包装进 Reference 包装器 |
const author = await em.findOne(Author, 1);
book.author = wrap(author).toReference();Schema 方法
| 方法 | 说明 |
|---|---|
getSchema() | 返回实体的 schema 名称 |
setSchema(schema?) | 设置实体的 schema 名称 |
访问内部属性
要访问 __meta 或 __em 这类内部属性,请把 true 作为第二个参数传入:
// 仅公开 API
wrap(author);
// 包含内部属性
wrap(author, true).__meta;
wrap(author, true).__em;用 assign() 更新实体
assign() 方法是最常用的辅助方法之一。它从普通对象更新实体的值,并自动处理关联——把 ID 转换成引用。
基础用法
不使用 assign() 时,更新关联需要手动创建引用:
const book = await em.findOne(Book, 1);
book.title = 'New Title';
book.author = em.getReference(Author, authorId);使用 assign() 时,你可以直接传入包含关联 ID 的普通数据:
wrap(book).assign({
title: 'New Title',
author: authorId, // 会被自动转换成引用
});这在处理用户输入或 API 载荷时尤其有用:
// 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);
});给未受管的实体赋值
对于尚未被 EntityManager 接管的实体,请在选项中传入 em:
const book = new Book();
wrap(book).assign({
title: 'New Book',
author: authorId,
}, { em });合并对象属性
默认情况下,assign() 会替换对象属性(与 Object.assign() 一样)。通过 mergeObjectProperties 启用深度合并:
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 关闭。
更新嵌套关联
要更新嵌套实体,请在数据中包含它的主键,并且确保它已在当前上下文中加载:
const book = await em.findOneOrFail(Book, 1, { populate: ['author'] });
// 更新已有的 author
wrap(book).assign({
author: {
id: book.author.id,
name: 'Updated Name',
},
});如果没有主键,嵌套对象会被视为新实体(触发 INSERT):
// 会创建一个新的 author
wrap(book).assign({
author: {
name: 'New Author',
},
});使用 updateByPrimaryKey: false 可以在不提供主键的情况下更新已有关联:
wrap(book).assign({
author: {
name: 'Updated Name',
},
}, { updateByPrimaryKey: false });更新集合
传入数组会替换集合元素,传入单个元素则会追加:
// 替换所有地址
wrap(user).assign({ addresses: [new Address(...), new Address(...)] });
// 追加到已有地址
wrap(user).assign({ addresses: new Address(...) });使用基于类的 DTO
当使用 class-validator 这类校验库时,请继承 PlainObject,让 MikroORM 把你的 DTO 当作普通对象处理:
import { PlainObject } from '@mikro-orm/core';
class UpdateBookDTO extends PlainObject {
@IsString()
title!: string;
@IsNumber()
authorId!: number;
}
// dto 是 UpdateBookDTO 的实例
wrap(book).assign(dto);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 实例(未受管实体必须提供) |
全局配置
在 ORM 配置中配置 assign() 的默认行为:
await MikroORM.init({
assign: {
updateNestedEntities: true,
updateByPrimaryKey: true,
mergeObjectProperties: false,
mergeEmbeddedProperties: true,
},
});