MikroORM7.2 中文文档
核心概念/使用实体管理器
已译 96/96

使用实体管理器

Persist 与 Flush

要理解 MikroORM 中持久化的工作方式,首先需要了解两个方法:em.persist() 与 em.flush()。

em.persist(entity) 用于把新实体标记为待持久化。它会让该实体被给定的 EntityManager 托管,一旦调用 flush,实体就会被写入数据库。

要理解 flush,先定义什么是受管实体:如果一个实体是从数据库中取回的(通过 em.find()、em.findOne(),或经由其他受管实体),或者是通过 em.persist() 注册为新实体的,那么它就是受管的。

em.flush() 会遍历所有受管实体,计算出相应的变更集,并执行对应的数据库查询。由于从数据库加载的实体会自动变为受管状态,你无需对它们调用 persist,只需 flush 就足以更新它们。

const book = await em.findOne(Book, 1);
book.title = 'How to persist things...';

// 无需 persist `book`,它已经被 EM 托管
await em.flush();

持久化与级联

要把实体状态保存到数据库,你需要持久化它。Persist 会决定使用 insert 还是 update,并计算出相应的变更集。尚未被持久化的实体引用(没有标识符)会被自动级联持久化。

// 在实体中使用构造函数来接收必填参数
const author = new Author('Jon Snow', 'snow@wall.st');
author.born = new Date();

const publisher = new Publisher('7K publisher');

const book1 = new Book('My Life on The Wall, part 1', author);
book1.publisher = publisher;
const book2 = new Book('My Life on The Wall, part 2', author);
book2.publisher = publisher;
const book3 = new Book('My Life on The Wall, part 3', author);
book3.publisher = publisher;

// 只需 persist 这些书,author 与 publisher 会被自动级联持久化
await em.persist([book1, book2, book3]).flush();

// 或者逐个 persist
em.persist(book1);
em.persist(book2);
em.persist(book3);
await em.flush(); // 一次性把所有内容 flush 到数据库

实体引用

MikroORM 把每个实体都表示为一个对象,即使是那些尚未完整加载的实体。它们被称为实体引用 —— 实际上就是普通的实体类实例,但只有主键可用。这使得无需查询数据库就能创建它们。引用和其他实体一样被存放在标识映射中。

const userRef = em.getReference(User, 1);
console.log(userRef);

这会输出类似 (User) { id: 1 } 的内容,注意类名被包在括号中 —— 这表示该实体处于未初始化状态,仅代表主键。

下面是使用引用代替完整加载实体的一些常见操作:

// 设置关系属性
author.favouriteBook = em.getReference(Book, 1);

// 通过引用移除实体
em.remove(em.getReference(Book, 2));

// 通过引用把实体加入集合
author.books.add(em.getReference(Book, 3));

这一概念可以与所谓的 Reference 包装器结合,以获得额外的类型安全,详见类型安全关系一节。

实体状态与 WrappedEntity

在实体发现阶段(即调用 MikroORM.init() 时),ORM 会修补实体原型,并为 WrappedEntity 生成一个惰性 getter —— 这是一个持有实体各类元数据与状态信息的类。每个实体实例都会有一个,通过隐藏的 __helper 属性暴露 —— 要以类型安全的方式访问其 API,请使用 wrap() 辅助函数:

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

const userRef = em.getReference(User, 1);
console.log('userRef is initialized:', wrap(userRef).isInitialized()); // false

await wrap(userRef).init();
console.log('userRef is initialized:', wrap(userRef).isInitialized()); // true

你也可以继承 MikroORM 提供的 BaseEntity。它定义了所有可通过 wrap() 辅助函数访问的公开方法,因此你可以直接调用 userRef.isInitialized() 或 userRef.init()。

WrappedEntity 实例还持有实体在加载或 flush 时刻的状态 —— 工作单元在 flush 期间正是用它来计算差异。另一个用途是序列化,你可以使用 toObject()、toPOJO() 与 toJSON() 方法把实体实例转换为普通 JavaScript 对象。

移除实体

要通过 EntityManager 删除实体,有两种方式:

  1. 通过 em.remove() 标记实体实例 —— 这意味着你首先需要持有该实体实例。不过别担心,即使不从数据库加载,你也能拿到一个 —— 通过 em.getReference()。
  2. 通过 em.nativeDelete() 发起 DELETE 查询 —— 当你只需要一条简单的删除查询时,用它就足够了。

我们先试试第一种方式,按实体实例移除:

// 使用引用就足够了,无需完整初始化的实体
const book1 = em.getReference(Book, 1);
await em.remove(book1).flush();

使用 EntityManager 获取实体

要从数据库获取实体,可以使用 em.find() 与 em.findOne():

const author = await em.findOne(Author, 123);
const books = await em.find(Book, {});

for (const author of authors) {
  console.log(author.name); // Jon Snow

  for (const book of author.books) {
    console.log(book.title); // 已初始化
    console.log(book.author.isInitialized()); // true
    console.log(book.author.id);
    console.log(book.author.name); // Jon Snow
    console.log(book.publisher); // 仅是引用
    console.log(book.publisher.isInitialized()); // false
    console.log(book.publisher.id);
    console.log(book.publisher.name); // undefined
  }
}

另外还有 em.findAll(),它没有第二个 where 参数,默认返回全部实体。不过你仍然可以使用该方法的 where 选项:

const books = await em.findAll(Book, {
  where: { publisher: { $ne: null } }, // 可选
});

要 populate 实体关系,可以使用 populate 参数。

const books = await em.findAll(Book, {
  where: { publisher: { $ne: null } },
  populate: ['author.friends'],
});

你也可以使用 em.populate() 辅助函数,在已加载的实体上 populate 关系(或确保它们被完整 populate)。通过 QueryBuilder 加载实体时这尤其方便:

const authors = await em.createQueryBuilder(Author).select('*').getResult();
await em.populate(authors, ['books.tags']);

// 现在 Author 实体的 `books` 集合已被 populate,
// 同时它们的 `tags` 集合也已被 populate。
console.log(authors[0].books[0].tags[0]); // 已初始化的 BookTag

条件对象(FilterQuery<T>)

通过条件对象查询实体(即 em.find(Entity, where: FilterQuery<T>) 中的 where)支持多种不同的写法:

// 按实体属性搜索
const users = await em.find(User, { firstName: 'John' });

// 按引用搜索时,可以直接使用主键
const id = 1;
const users = await em.find(User, { organization: id });

// 或者传入未 populate 的引用(包括 `Reference` 包装器)
const ref = await em.getReference(Organization, id);
const users = await em.find(User, { organization: ref });

// 也支持完整 populate 的实体
const ent = await em.findOne(Organization, id);
const users = await em.find(User, { organization: ent });

// 带运算符的复杂查询
const users = await em.find(User, { $and: [{ id: { $nin: [3, 4] } }, { id: { $gt: 2 } }] });

// 也可以直接按主键数组搜索
const users = await em.find(User, [1, 2, 3, 4, 5]);

// 在 findOne 中上述写法都可用,此外还可以按单个主键搜索
const user1 = await em.findOne(User, 1);

如第五个示例所示,你还可以使用 $and、$or、$gte、$gt、$lte、$lt、$in、$nin、$eq、$ne、$like、$re 与 $fulltext 等运算符。更多内容请参见查询条件一节。

在 FilterQuery 中使用自定义类

如果你决定用自己的对象来抽象过滤选项,那么可能会遇到 find 选项无法返回预期结果的问题。这是因为 FilterQuery 应当以普通对象(POJO)的形式提供,而不是带原型的类实例。

如果你想提供自己的 FilterQuery DTO,那么该 DTO 类应当继承 PlainObject 类。这样 MikroORM 就知道应当把它当作普通对象处理。

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

class Filter extends PlainObject {
  name: string;
}

const where = new Filter();
where.name = 'Jon';
const res = await em.find(Author, where);

缓解 Type instantiation is excessively deep and possibly infinite.ts(2589) 错误

有时你可能会遇到因查询过于复杂、TypeScript 无法正确推断所有类型而导致的错误。通常可以通过显式提供类型参数来解决。

你也可以选择改用仓库,因为在那里类型推断不会有太大问题。

作为最后的手段,你随时可以把查询强制转换为 any。

const books = await em.find<Book>(Book, { ... our complex query ... });
// 或
const books = await em.getRepository(Book).find({ ... our complex query ... });
// 或
const books = await em.find<any>(Book, { ... our complex query ... }) as Book[];

你可能遇到的另一个问题是 TypeScript 编译期间抛出 RangeError: Maximum call stack size exceeded 错误(通常来自 node_modules/typescript/lib/typescript.js 文件)。解决办法相同,显式提供类型参数即可。

按被引用实体的字段搜索

你也可以按被引用实体的属性搜索。只需像这样传入嵌套的 where 条件,所有请求的关系都会被自动 join。目前它只会 join 这些表以便你搜索和排序。若要 populate 实体,别忘了同时传入 populate 参数。

// 查找某本书的作者,该书带有按名称指定的标签
const author = await em.findOne(Author, { books: { tags: { name: 'Tag name' } } });
console.log(author.books.isInitialized()); // false,因为它只用于查询和排序

const author = await em.findOne(Author, { books: { tags: { name: 'Tag name' } } }, { populate: ['books.tags'] });
console.log(author.books.isInitialized()); // true,因为它已被 populate
console.log(author.books[0].tags.isInitialized()); // true,因为它已被 populate
console.log(author.books[0].tags[0].isInitialized()); // true,因为它已被 populate

该特性仅在 SQL 驱动下完全可用。在 MongoDB 中你始终需要从拥有方发起查询 —— 因此在上面的示例中,需要先按名称加载标签,再加载关联的书,最后加载作者。另一种选择是对 schema 做反规范化。

部分加载

要只获取部分数据库列,可以使用 fields 选项:

const author = await em.findOne(Author, '...', {
  fields: ['name', 'born'],
});
console.log(author.id); // 主键总是会被选中
console.log(author.name); // Jon Snow
console.log(author.email); // undefined

这对嵌套关系同样有效:

const author = await em.findOne(Author, '...', {
  fields: ['name', 'books.title', 'books.author', 'books.price'],
});

即使你省略主键,它们也总会被选中。另一方面,选择外键是你的责任 —— 如果你省略了这类属性,关系可能无法被正确加载。在下面的示例中,books 不会与 author 关联起来,因为你没有指定要加载 books.author 字段。

// 这会同时加载 author 与 book 实体,但由于 select 中缺少外键,它们不会被关联起来
const author = await em.findOne(Author, '...', {
  fields: ['name', 'books.title', 'books.price'],
});

同样的问题在 MongoDB 的 M:N 集合中也会出现 —— 它们以数组属性的形式存储在拥有方实体上,因此你需要确保把这些属性也标记上。

const author = await em.findOne(Author, '...', {
  fields: ['name', 'books.title', 'books.author', 'books.price'],
});

或者,你也可以使用 exclude 选项,它会排除指定的属性并选中其余全部内容:

const author = await em.findOne(Author, '...', {
  exclude: ['email', 'books.price'],
  populate: ['books'], // 与 `fields` 不同,这里你需要显式 populate 该关系
});

获取分页结果

如果你打算对结果做分页,可以使用 em.findAndCount(),它会返回应用 limit 与 offset 之前的实体总数。

const [authors, count] = await em.findAndCount(Author, { ... }, { limit: 10, offset: 50 });
console.log(authors.length); // 基于 limit 参数,例如 10
console.log(count); // 总数,例如 1327

基于游标的分页

作为使用 limit 与 offset 的偏移量分页的替代方案,你可以基于游标进行分页。游标是一个不透明字符串,定义了有序实体图中的特定位置。你可以通过 em.findByCursor() 使用这些选项。在底层,它会像 em.findAndCount() 一样调用 em.find() 与 em.count(),但改用游标选项。

它支持 before、after、first 与 last 选项,同时禁止使用 limit 与 offset。必须显式提供 orderBy 选项。它还支持 includeCount 选项(默认为 true)。当显式设为 false 时,实体管理器会执行 find 而非 findAndCount。此时游标的 totalCount 会被设为 null。当知道确切页数并不重要时,这可以作为性能优化手段,避免昂贵的 SQL count 查询。

使用 first 与 after 进行正向分页,或使用 last 与 before 进行反向分页。

  • first 与 last 是数字,作为 offset 的替代方案,这两个选项互斥,一次只能用一个
  • before 与 after 指定上一个游标值,它可以是以下之一:
    • Cursor 实例
    • 由 startCursor/endCursor 属性提供的不透明字符串
    • POJO / 实体实例
const currentCursor = await em.findByCursor(User, {
  first: 10,
  after: previousCursor, // 游标实例
  orderBy: { id: 'desc' },
});

// 获取下一页
const nextCursor = await em.findByCursor(User, {
  first: 10,
  after: currentCursor.endCursor, // 不透明字符串
  orderBy: { id: 'desc' },
});

// 获取下一页
const nextCursor2 = await em.findByCursor(User, {
  first: 10,
  after: { id: lastSeenId }, // 类实体的 POJO
  orderBy: { id: 'desc' },
});

const currentCursorWithoutCount = await em.findByCursor(User, {
  first: 10,
  after: previousCursor, // 游标实例
  orderBy: { id: 'desc' },
  includeCount: false,
});

Cursor 对象提供如下接口:

Cursor<User> {
  items: [
    User { ... },
    User { ... },
    User { ... },
    ...
  ],
  totalCount: 50, // 当 `includeCount` 设为 false 时未定义
  length: 10,
  startCursor: 'WzRd',
  endCursor: 'WzZd',
  hasPrevPage: true,
  hasNextPage: true,
}

游标中包含什么

startCursor/endCursor 字符串是不透明的,但并未加密:它们持有该行 orderBy 值的 base64url 编码 JSON,因此任何持有游标的人都能解码它。这适用于 orderBy 中的每个键,包括嵌套关系与内嵌路径(例如 orderBy: { author: { email: 'asc' } })。按关系本身排序时会存储其主键。

hidden 标记只影响实体的序列化,构建游标时并不会参考它。因此,作为排序键的隐藏属性依然会成为游标值的一部分,尽管 serialize() 与 toJSON() 会把它从元素中省略:

const cursor = await em.findByCursor(User, {
  first: 10,
  orderBy: { internalRank: 'asc' }, // `internalRank` 被标记为 `hidden: true`
});

Cursor.decode(cursor.endCursor!); // [42]

如果游标会被交给客户端,请只按客户端有权看到的值排序,或者把游标保留在服务端(或对其加密),改为下发你自己的令牌。

流式查询

如果你想处理大量实体而不必一次性把它们全部载入内存,可以使用 em.stream() 方法。它返回一个异步可迭代对象,因此你可以在 for await ... of 循环中使用它。

const stream = em.stream(Book, {
  populate: ['author'],
  where: { price: { $gt: 100 } },
  orderBy: { id: 'ASC' },
});

for await (const book of stream) {
  console.log(book.title);
  console.log(book.author.name);
}

使用流式查询时有若干限制:

  • 返回的实体不受管。标识性仅在返回的实体图内部成立。
  • 所有被 populate 的关系都会强制使用 join 策略。
  • 当 populate to-many 关系时,只会返回完整水合的实体。
  • 你应当提供 orderBy 子句以保证顺序一致。
  • 在 mongodb 驱动下,只有根实体可以被流式处理,populate 选项会被忽略。

要逐行流式获取结果,请使用 mergeResults: false 选项。在此模式下,如果你 populate 了 to-many 关系,会得到重复的根实体,每一行对应一个(这是由 to-many join 导致的笛卡尔积造成的)。

const stream = em.stream(Book, {
  populate: ['author'],
  where: { price: { $gt: 100 } },
  orderBy: { id: 'ASC' },
  mergeResults: false,
});

要流式获取原始结果,请直接使用 QueryBuilder.stream() 或 driver.stream() 方法。更多内容请阅读流式查询指南。

处理未找到的实体

当你调用 em.findOne() 而根据条件没有找到任何实体时,会返回 null。如果你更希望抛出一个 Error 实例,可以使用 em.findOneOrFail():

const author = await em.findOne(Author, { name: 'does-not-exist' });
console.log(author === null); // true

try {
  const author = await em.findOneOrFail(Author, { name: 'does-not-exist' });
  // 这里 author 一定已经找到
} catch (e) {
  console.error('Not found', e);
}

你可以通过 findOneOrFailHandler 选项全局自定义错误,也可以在 findOneOrFail 调用中通过 failHandler 选项局部自定义。

try {
  const author = await em.findOneOrFail(Author, { name: 'does-not-exist' }, {
    failHandler: (entityName: string, where: Record<string, any> | IPrimaryKey) => new Error(`Failed: ${entityName} in ${util.inspect(where)}`)
  });
} catch (e) {
  console.error(e); // 你的自定义错误
}

使用自定义 SQL 片段

WHERE 查询或 ORDER BY 子句中的任何 SQL 片段都需要用 raw() 或 sql 包裹:

const users = await em.find(User, { [sql`lower(email)`]: 'foo@bar.baz' }, {
  orderBy: { [sql`(point(loc_latitude, loc_longitude) <@> point(0, 0))`]: 'ASC' },
});

这会生成如下查询:

select `e0`.*
from `user` as `e0`
where lower(email) = 'foo@bar.baz'
order by (point(loc_latitude, loc_longitude) <@> point(0, 0)) asc

更多内容请参见使用原始 SQL 查询片段一节。

分组计数

使用 em.countBy() 可以按一个或多个属性对实体分组计数。它不会发起 N 条独立的计数查询,而是在 SQL 驱动上发出一条 GROUP BY 查询,在 MongoDB 上则使用聚合管道:

// 统计每位作者的书籍数量
const counts = await em.countBy(Book, 'author');
// { '1': 2, '2': 1, '3': 3 }

// 带过滤条件计数
const counts = await em.countBy(Book, 'author', { where: { active: true } });
// { '1': 1, '3': 2 }

// 复合 groupBy —— 键以 ~~~ 连接
const counts = await em.countBy(Order, ['status', 'country']);
// { 'pending~~~US': 5, 'shipped~~~DE': 3 }

仓库上也提供了同样的方法:

const counts = await em.getRepository(Book).countBy('author');

查询选项

em.find() 与 em.count() 方法接受若干驱动专属的查询选项:

排序规则(Collation)

控制字符串比较规则。collation 选项根据驱动不同接受不同类型:

  • SQL 驱动:传入排序规则名称字符串。它会作为 COLLATE 应用到 ORDER BY 子句中的每一列。向 SQL 驱动传入 CollationOptions 对象会抛出错误。
  • MongoDB:传入 CollationOptions 对象。向 MongoDB 传入字符串会抛出错误。
// SQL:把 COLLATE 应用于 ORDER BY
const users = await em.find(User, {}, {
  collation: 'utf8mb4_general_ci',
  orderBy: { name: 'asc' },
});
// 生成:... ORDER BY `name` COLLATE `utf8mb4_general_ci` ASC

// MongoDB:结构化的排序规则对象
const users = await em.find(User, {}, {
  collation: { locale: 'en', strength: 2 },
  orderBy: { name: QueryOrder.ASC },
});

要在 WHERE 条件中使用排序规则(仅 SQL),请使用原始 SQL 片段:

const users = await em.find(User, {
  [sql`name collate utf8mb4_general_ci`]: 'john',
});
// 生成:... WHERE name collate `utf8mb4_general_ci` = 'john'

对于 MongoDB,collation 选项会应用于整个查询(过滤与排序皆然),这是 MongoDB 的原生行为。

索引提示

对于 SQL,传入一个字符串,它会被追加到 FROM 子句之后。对于 MongoDB,传入字符串(索引名)或对象(索引规格)作为 hint 传给原生驱动。

// SQL
const users = await em.find(User, {}, {
  indexHint: 'force index(my_index)',
});

// MongoDB
const users = await em.find(User, {}, {
  indexHint: 'name_1', // 或 { name: 1 }
});

通过 using 指定具名索引提示

using 选项是 indexHint 的更高层替代方案。你传入一个已声明索引的名称,MikroORM 会做三件事:

  1. 校验该索引确实存在于实体上。
  2. 校验 where / orderBy 中用到的每个属性都被该索引覆盖 —— 拼写错误与意外未走索引的查询会变成编译期与运行时错误,而不是静默的全表扫描。
  3. 为你生成驱动专属的 SQL 提示(MySQL/MariaDB 上是 USE INDEX (...),MSSQL 上是 WITH (INDEX(...)),MongoDB 上是 hint 选项,PostgreSQL / SQLite / libSQL 上仅做校验)。
// 单个索引
const users = await em.find(User, { name: 'foo' }, {
  using: 'idx_user_name',
});

// 多个索引 —— where/orderBy 可以使用它们所覆盖属性的并集
const users = await em.find(User, { name: 'foo', email: 'bar@x' }, {
  using: ['idx_user_name', 'uniq_user_email'],
});

该选项对所有读取方法都有效:find、findOne、findOneOrFail、findAndCount、findAll、findByCursor、stream,以及 EntityRepository 上对应的方法。

要获得类型安全的 using,需要在实体上声明可用索引 —— 参见索引页面中的查询时索引提示。

using 与 indexHint 可以同时使用:两者都设置时,indexHint 生效并原样输出它的原始字符串。using 仍会针对具名索引校验 where / orderBy,这在你想要运行时检查、但又需要手动写出非标准提示时很有用:

await em.find(User, { name: 'foo' }, {
  using: 'idx_user_name',                        // 仅校验
  indexHint: 'force index for join (idx_user_name)', // 原样输出
});

如果具名索引不存在,或者 where / orderBy 引用了该索引未覆盖的属性,MikroORM 会抛出清晰的错误,列出可用索引与出问题的属性。

MongoDB 每个查询只接受单个索引 —— 传入数组会抛出异常。对于 SQLite / libSQL,该选项仅做校验(这些引擎没有提供从 SELECT 语句中强制使用某个索引的公开方式)。

MongoDB 专属选项

const users = await em.find(User, {}, {
  maxTimeMS: 5000,     // 查询超时时间(毫秒)
  allowDiskUse: true,  // 允许在大型排序中使用磁盘
});

Union Where(仅 SQL)

unionWhere 选项提供了对索引友好的 $or 替代方案。它不会生成带 OR 条件的单条查询(这可能阻止索引生效),而是生成一个 UNION ALL 子查询,其中每个分支都可以独立使用自己的索引。

// 不用:{ $or: [{ name: 'Alice' }, { email: 'bob@test.com' }] }
// 改用 unionWhere 以更好地利用索引:
const users = await em.find(User, {}, {
  unionWhere: [
    { name: 'Alice' },
    { email: 'bob@test.com' },
  ],
});

这会生成类似如下的 SQL:

SELECT ... FROM `user` WHERE `id` IN (
  (SELECT `id` FROM `user` WHERE `name` = 'Alice')
  UNION ALL
  (SELECT `id` FROM `user` WHERE `email` = 'bob@test.com')
)

你可以使用 unionWhereStrategy: 'union' 在数据库层面对各分支的结果去重。这会增加一次排序与去重步骤,因此只有当分支重叠度非常高且总行数很大时才值得:

const users = await em.find(User, {}, {
  unionWhere: [
    { name: 'Alice' },
    { email: 'bob@test.com' },
  ],
  unionWhereStrategy: 'union',
});

unionWhere 同样适用于 nativeUpdate 与 nativeDelete:

// 仅更新匹配 union 分支的用户
await em.nativeUpdate(User, {}, { active: false }, {
  unionWhere: [
    { lastLogin: { $lt: oneYearAgo } },
    { banned: true },
  ],
});

// 仅删除匹配 union 分支的用户
await em.nativeDelete(User, {}, {
  unionWhere: [
    { expired: true },
    { email: { $like: '%@spam.com' } },
  ],
});

unionWhere 中的每个分支都会被独立处理,因此关系条件与实体过滤器都会在各自分支的子查询中生效。

unionWhere 仅在 SQL 驱动上受支持,在 MongoDB 中使用会抛出错误。

更新引用(未加载的实体)

你可以通过工作单元更新引用,就像更新一个已加载的实体一样。这样无需加载实体也能发起更新查询。

const ref = em.getReference(Author, 123);
ref.name = 'new name';
ref.email = 'new email';
await em.flush();

这与调用 em.nativeUpdate() 大致等价,但有一个重要区别 —— 它使用 flush 操作,而 flush 会处理事件执行,因此所有生命周期钩子以及 flush 事件都会被触发。

通过 raw() 辅助函数进行原子更新

当你想通过 flush 发起原子更新查询时,可以使用静态的 raw() 辅助函数:

const ref = em.getReference(Author, 123);
ref.age = raw<number>(`age * 2`);

await em.flush();
console.log(ref.age); // flush 之后即可获得真实值

raw() 辅助函数接受一个泛型类型参数,用于指定返回类型。当直接赋值给实体属性时,请使用 raw<T>(),其中 T 与属性类型一致:

// 直接给属性赋值需要显式类型
author.age = raw<number>(`age + 1`);
author.name = raw<string>(`upper(name)`);
book.price = raw<number>(`price * 1.1`);

使用 em.create()、em.assign() 等方法时不需要类型参数,因为 RawQueryFragment 已被实体数据类型所接受:

// 使用 em.create/em.assign 时无需显式类型
em.assign(author, { age: raw(`age + 1`) });
const book = em.create(Book, { price: raw(`price * 1.1`) });

raw() 辅助函数返回一个特殊的原始查询片段对象。它不允许你操作该值:除了把它用作对象键之外,把它转换为原始类型都会抛出错误。该值只能被使用一次,如果你尝试把它重新赋值给另一个实体,会抛出错误以防止你犯下这类错误:

order.number = raw<number>(`(select max(num) + 1 from orders)`);
user.lastOrderNumber = order.number; // 抛出异常,它可能解析出不同的值
JSON.stringify(order); // 抛出异常,raw 值无法被序列化

Upsert

你可以使用 em.upsert() 根据实体是否已存在于数据库中来创建或更新它。该方法执行一条 insert on conflict merge 查询以确保数据库同步,并返回一个受管的实体实例。该方法既接受 entityName 加实体 data,也接受仅一个实体实例。

// insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 33
const author = await em.upsert(Author, { email: 'foo@bar.com', age: 33 });

实体数据需要包含主键,或任意其他唯一属性。让我们看下面的示例,其中 Author.email 是唯一属性:

// insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 33
// select "id" from "author" where "email" = 'foo@bar.com'
const author = await em.upsert(Author, { email: 'foo@bar.com', age: 33 });

根据驱动支持情况的不同,它会使用 returning 查询或单独的 select 查询来获取主键(如果 data 中缺少主键)。

你也可以传入游离的实体实例,在 em.upsert() 调用之后它会变为受管状态。

const author = em.create(Author, { email: 'foo@bar.com', age: 33 });
await em.upsert(author);

还有一个签名相似的 em.upsertMany():

const [author1, author2, author3] = await em.upsertMany(Author, [
  { email: 'a1', age: 41 },
  { email: 'a2', age: 42 },
  { email: 'a3', age: 43 },
]);

默认情况下,EntityManager 会优先使用主键,并回退到第一个有值的唯一属性。有时这可能不是你想要的行为,一个例子是你通过属性初始化器生成主键,例如使用 uuid.v4()。针对这些高级场景,你可以通过以下选项控制底层 upsert 逻辑的工作方式:

  • onConflictFields?: (keyof T)[] 用于控制 conflict 子句
  • onConflictAction?: 'ignore' | 'merge',取值为 ignore 与 merge,因为 QB 方法就是这样命名的
  • onConflictMergeFields?: (keyof T)[] 用于控制 merge 子句
  • onConflictExcludeFields?: (keyof T)[] 用于从 merge 子句中省略字段
  • onConflictWhere?: FilterQuery<T> 用于支持条件更新
const [author1, author2, author3] = await em.upsertMany(Author, [{ ... }, { ... }, { ... }], {
  onConflictFields: ['email'], // 指定传给 on conflict 子句的字段集合
  onConflictAction: 'merge',
  onConflictExcludeFields: ['id'],
});

这会生成类似如下的查询:

insert into "author"
  ("id", "current_age", "email", "foo")
  values
    (1, 41, 'a1', true),
    (2, 42, 'a2', true),
    (5, 43, 'a3', true)
  on conflict ("email")
  do update set
    "current_age" = excluded."current_age",
    "foo" = excluded."foo"
  returning "_id", "current_age", "foo", "bar"

由属性 onCreate 钩子生成的值(即未为该属性提供值时)只用于查询的 insert 部分 —— 它们会被自动排除在 merge 子句之外,因此绝不会覆盖已存在行的值。

onConflictWhere 选项允许你为冲突目标添加 WHERE 子句,从而基于已有数据实现条件更新。这在乐观锁或基于版本的更新等场景中很有用,你只想在满足特定条件时才更新。

await em.upsert(Document, {
  name: 'doc1',
  version: 2,
  content: 'updated content',
}, {
  onConflictFields: ['name'],
  onConflictWhere: { version: { $lt: 2 } },
});

克隆实体

em.clone() 通过 INSERT ... SELECT 在数据库层面复制行,无需把数据往返传输到 Node.js。它返回一个已水合、且已注册到标识映射中的实体。

// clone(EntityClass, where, overrides?, options?)
const cloned = await em.clone(Author, { id: 1 }, { email: 'new@email.com' });

// clone(entity, overrides?, options?)
const author = await em.findOneOrFail(Author, 1);
const cloned = await em.clone(author, { email: 'new@email.com' });

// 纯克隆(无覆盖)—— 所有非主键字段都会被复制
const cloned = await em.clone(Author, { id: 1 });

where 参数是常规的 FilterQuery<T> —— 与 em.find() 接受的结构相同。当你传入实体实例而非实体类时,会自动使用该实体的主键作为 where 子句。

overrides 参数是一个 EntityData<T> 局部对象,用于替换克隆行中的指定列。它通常用于满足唯一约束(例如唯一的 email),或为克隆出的行标记新值:

const cloned = await em.clone(
  Author,
  { id: 1 },
  { email: 'cloned@example.com', age: 99 },
);

哪些内容会被克隆:

  • 自增主键会被排除 —— 数据库会为克隆行分配新的主键。
  • 内嵌属性会被复制(它们位于同一行上)。
  • M:1 外键会被保留(两行指向同一个父实体)。
  • 版本属性会被重置为初始值。
  • 生成列 / persist: false / 公式列会被排除。
  • M:N 与 1:M 关系不会被克隆 —— 中间表行与反向端行仍附着在原实体上。如果你需要它们,请随后显式调用 em.persist()。

克隆支持单表继承与每类型一张表(TPT)继承 —— 对于 TPT,MikroORM 会为每个祖先表生成一条 INSERT ... SELECT,以便在每张表中重建完整行。

所有 SQL 驱动(SQLite、libSQL、PostgreSQL、MySQL、MariaDB、MSSQL)都会执行服务端的 INSERT ... SELECT。MongoDB 则回退为 find + insertOne 的往返方式,最终形态相同。

关于更底层的构建块,请参见 Query Builder 中的 qb.insertFrom() —— 它会生成 em.clone() 所基于的原始 INSERT ... SELECT 语句。

刷新实体状态

你可以使用 em.refresh(entity) 让实体状态与数据库同步。它相当于调用带 refresh: true 且禁用自动 flush 的 em.findOne() 的快捷方式。

这会导致对该实体所做的任何更改丢失。

const author = await em.findOneOrFail(Author, { name: 'Jon' });
console.log(author.name); // 'Jon'

// 对实体的修改将会丢失!
author.name = '123';

// 刷新该值,忽略任何修改
await em.refresh(author);
console.log(author.name); // 'Jon'

批量插入、更新与删除

当你 flush 对某一实体类型所做的修改时,每种操作(create/update/delete)只会执行一条查询。

for (let i = 1; i <= 5; i++) {
  const u = new User(`Peter ${i}`, `peter+${i}@foo.bar`);
  em.persist(u);
}

await em.flush();

// insert into `user` (`name`, `email`) values
//   ('Peter 1', 'peter+1@foo.bar'),
//   ('Peter 2', 'peter+2@foo.bar'),
//   ('Peter 3', 'peter+3@foo.bar'),
//   ('Peter 4', 'peter+4@foo.bar'),
//   ('Peter 5', 'peter+5@foo.bar');
for (const user of users) {
  user.name += ' changed!';
}

await em.flush();

// update `user` set
//   `name` = case
//     when (`id` = 1) then 'Peter 1 changed!'
//     when (`id` = 2) then 'Peter 2 changed!'
//     when (`id` = 3) then 'Peter 3 changed!'
//     when (`id` = 4) then 'Peter 4 changed!'
//     when (`id` = 5) then 'Peter 5 changed!'
//     else `priority` end
//   where `id` in (1, 2, 3, 4, 5)
em.remove(users);
await em.flush();

// delete from `user` where `id` in (1, 2, 3, 4, 5)

禁用标识映射与变更集跟踪

有时你可能想为某个查询禁用标识映射与变更集跟踪。这可以通过 disableIdentityMap 选项实现。在底层,它会创建一个新的上下文,在其中加载实体,随后将其清空,因此主标识映射会保持干净。

与受管实体相对,这类实体被称为游离(detached)实体。要操作它们,你首先需要通过 em.merge() 合并它们。

const users = await em.find(User, { email: 'foo@bar.baz' }, {
  disableIdentityMap: true,
  populate: ['cars.brand'],
});
users[0].name = 'changed';
await em.flush(); // 调用 flush 没有任何效果,因为该实体不受管

在手动映射原始数据库结果时同样可以使用该选项。这在 CDC 处理等场景中很有用:前置镜像(before-image)应当被转换为实体但不影响当前上下文,而后置镜像(after-image)仍可使用默认的受管行为。

const before = em.map(User, beforeRow, { disableIdentityMap: true });
const after = em.map(User, afterRow);

请记住,这也可能对性能产生负面影响。

实体仓库

虽然你可以直接使用 EntityManager,但更便捷的方式是改用 EntityRepository。你可以把仓库注册到诸如 InversifyJS 这样的依赖注入容器中,这样就不必每次都从 EntityManager 获取它们。

更多示例请查看 tests/EntityManager.mongo.test.ts 或 tests/EntityManager.mysql.test.ts。

自定义属性排序

实体属性通过 customOrder 属性提供了一些自定义排序支持。这对于那些自然顺序与其底层数据表示不一致的值很有用。考虑下面的代码,自然排序顺序会是 high、low、medium。然而你可以提供 customOrder 来指明这些枚举值应当如何排序。

enum Priority {
  Low = 'low',
  Medium = 'medium',
  High = 'high',
}

@Entity()
class Task {
  @PrimaryKey()
  id!: number

  @Property()
  label!: string

  @Enum({
    items: () => Priority,
    customOrder: [Priority.Low, Priority.Medium, Priority.High]
  })
  priority!: Priority
}

// ...

em.create(Task, { label: 'A', priority: Priority.Low }),
em.create(Task, { label: 'B', priority: Priority.Medium }),
em.create(Task, { label: 'C', priority: Priority.High })
await em.flush();

const tasks = await em.find(Task, {}, { orderBy: { priority: QueryOrder.ASC } });
for (const t of tasks) {
  console.log(t.label);
}
// 输出 A、B、C

扩展 EntityManager

要用你自己的自定义方法扩展 EntityManager,可以使用 entityManager 这个 ORM 选项:

import { MikroORM, EntityManager } from '@mikro-orm/sqlite';

class MyEntityManager extends EntityManager {

  myCustomMethod(base: number): number {
    return base * Math.random();
  }

}

const orm = await MikroORM.init({
  entities: [...],
  dbName: ':memory:',
  entityManager: MyEntityManager,
});
console.log(orm.em instanceof MyEntityManager); // true
const res = orm.em.myCustomMethod(123);