MikroORM7.2 中文文档
Schema 与数据库/虚拟实体
已译 96/96

虚拟实体

虚拟实体不代表任何数据库表。相反,它们会动态解析为一条 SQL 查询(或 MongoDB 中的一个聚合),从而可以把任何类型的结果映射到实体上。这类实体仅用于读取,它们没有主键,因此无法被追踪变更。

如果你需要由 schema 生成器创建并管理的真实数据库视图,请改看视图实体。视图实体会创建 CREATE VIEW 语句并被纳入迁移追踪,而虚拟实体会在查询时求值其表达式。

虚拟实体可以包含标量属性,也可以包含 to-one 关联(M:1 与 1:1 的拥有端)。这类关联始终通过 select-in 策略填充。

要定义虚拟实体,需要提供一个 expression,既可以是字符串(SQL 查询):

你需要使用基于当前命名策略的虚拟列名。注意 authorName 属性被表示为 author_name 列。

./entities/BookWithAuthor.ts
import { defineEntity, p } from '@mikro-orm/core';

const BookWithAuthorSchema = defineEntity({
  name: 'BookWithAuthor',
  expression: `
    select b.title, a.name as author_name,
    (
      select group_concat(distinct t.name)
      from book b 
      join tags_ordered bt on bt.book_id = b.id
      join book_tag t on t.id = bt.book_tag_id
      where b.author_id = a.id
      group by b.author_id
    ) as tags
    from author a
    group by a.id
  `,
  properties: {
    title: p.string(),
    authorName: p.string(),
    tags: p.type('string[]').$type<string[]>(),
  },
});

export class BookWithAuthor extends BookWithAuthorSchema.class {}
BookWithAuthorSchema.setClass(BookWithAuthor);
./entities/BookWithAuthor.ts
import { type InferEntity, defineEntity, p } from '@mikro-orm/core';

export const BookWithAuthor = defineEntity({
  name: 'BookWithAuthor',
  expression: `
    select b.title, a.name as author_name,
    (
      select group_concat(distinct t.name)
      from book b 
      join tags_ordered bt on bt.book_id = b.id
      join book_tag t on t.id = bt.book_tag_id
      where b.author_id = a.id
      group by b.author_id
    ) as tags
    from author a
    group by a.id
  `,
  properties: {
    title: p.string(),
    authorName: p.string(),
    tags: p.type('string[]').$type<string[]>(),
  },
});

export type IBookWithAuthor = InferEntity<typeof BookWithAuthor>;
./entities/BookWithAuthor.ts
@Entity({
  expression: `
    select b.title, a.name as author_name,
    (
      select group_concat(distinct t.name)
      from book b 
      join tags_ordered bt on bt.book_id = b.id
      join book_tag t on t.id = bt.book_tag_id
      where b.author_id = a.id
      group by b.author_id
    ) as tags
    from author a
    group by a.id
  `
})
export class BookWithAuthor {

  @Property()
  title!: string;

  @Property()
  authorName!: string;

  @Property()
  tags!: string[];

}
./entities/BookWithAuthor.ts
@Entity({
  expression: `
    select b.title, a.name as author_name,
    (
      select group_concat(distinct t.name)
      from book b 
      join tags_ordered bt on bt.book_id = b.id
      join book_tag t on t.id = bt.book_tag_id
      where b.author_id = a.id
      group by b.author_id
    ) as tags
    from author a
    group by a.id
  `
})
export class BookWithAuthor {

  @Property()
  title!: string;

  @Property()
  authorName!: string;

  @Property()
  tags!: string[];

}

也可以是一个回调:

./entities/BookWithAuthor.ts
const BookWithAuthorSchema = defineEntity({
  name: 'BookWithAuthor',
  expression: (em: EntityManager) => {
    return em.createQueryBuilder(Book, 'b')
      .select(['b.title', 'a.name as author_name', 'group_concat(t.name) as tags'])
      .join('b.author', 'a')
      .join('b.tags', 't')
      .groupBy('b.id');
  },
  properties: {
    title: p.string(),
    authorName: p.string(),
    tags: p.type('string[]').$type<string[]>(),
  },
});

export class BookWithAuthor extends BookWithAuthorSchema.class {}
BookWithAuthorSchema.setClass(BookWithAuthor);
./entities/BookWithAuthor.ts
export const BookWithAuthor = defineEntity({
  name: 'BookWithAuthor',
  expression: (em: EntityManager) => {
    return em.createQueryBuilder(Book, 'b')
      .select(['b.title', 'a.name as author_name', 'group_concat(t.name) as tags'])
      .join('b.author', 'a')
      .join('b.tags', 't')
      .groupBy('b.id');
  },
  properties: {
    title: p.string(),
    authorName: p.string(),
    tags: p.type('string[]').$type<string[]>(),
  },
});
./entities/BookWithAuthor.ts
@Entity({
  expression: (em: EntityManager) => {
    return em.createQueryBuilder(Book, 'b')
      .select(['b.title', 'a.name as author_name', 'group_concat(t.name) as tags'])
      .join('b.author', 'a')
      .join('b.tags', 't')
      .groupBy('b.id');
  },
})
export class BookWithAuthor {

  @Property()
  title!: string;

  @Property()
  authorName!: string;

  @Property()
  tags!: string[];

}
./entities/BookWithAuthor.ts
@Entity({
  expression: (em: EntityManager) => {
    return em.createQueryBuilder(Book, 'b')
      .select(['b.title', 'a.name as author_name', 'group_concat(t.name) as tags'])
      .join('b.author', 'a')
      .join('b.tags', 't')
      .groupBy('b.id');
  },
})
export class BookWithAuthor {

  @Property()
  title!: string;

  @Property()
  authorName!: string;

  @Property()
  tags!: string[];

}

在 MongoDB 中,你可以使用聚合,不过由于其特性,用起来并不太符合直觉。下面的示例大致等价于前面的 SQL 版本。

where 查询以及 orderBy、limit、offset 等选项都需要你在管道中显式处理。

@Entity({
  expression: (em: EntityManager, where, options) => {
    const $sort = { ...options.orderBy } as Dictionary;
    $sort._id = 1;
    const pipeline: Dictionary[] = [
      { $project: { _id: 0, title: 1, author: 1 } },
      { $sort },
      { $match: where ?? {} },
      { $lookup: { from: 'author', localField: 'author', foreignField: '_id', as: 'author', pipeline: [{ $project: { name: 1 } }] } },
      { $unwind: '$author' },
      { $set: { authorName: '$author.name' } },
      { $unset: ['author'] },
    ];

    if (options.offset != null) {
      pipeline.push({ $skip: options.offset });
    }

    if (options.limit != null) {
      pipeline.push({ $limit: options.limit });
    }

    return em.aggregate(Book, pipeline);
  },
})
export class BookWithAuthor {

  @Property()
  title!: string;

  @Property()
  authorName!: string;

}