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

视图实体

视图实体代表由 MikroORM 的 schema 生成器创建并管理的真实数据库视图。与在查询时求值表达式的虚拟实体不同,视图实体会在你的数据库中创建持久的 CREATE VIEW 语句。

虚拟实体与视图实体对比

FeatureVirtual EntitiesView Entities
数据库对象无(表达式在查询时求值)真实的数据库视图
主键不允许允许
Schema 生成被忽略会生成 CREATE VIEW / DROP VIEW
迁移不被追踪被追踪与 diff
只读是是
使用场景动态查询、聚合可复用视图、复杂查询、遗留视图

定义视图实体

要定义视图实体,需要同时设置 view: true 并提供 expression。表达式定义了支撑该视图的 SQL 查询。如果没有 view: true,只有 expression 的实体会成为虚拟实体(表达式在查询时求值,不会创建任何数据库对象)。

使用字符串表达式

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

const AuthorStatsSchema = defineEntity({
  name: 'AuthorStats',
  tableName: 'author_stats_view',
  view: true,
  expression: `
    select a.name, count(b.id) as book_count
    from author a
    left join book b on b.author_id = a.id
    group by a.id, a.name
  `,
  properties: {
    name: p.string().primary(),
    bookCount: p.integer(),
  },
});

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

export const AuthorStats = defineEntity({
  name: 'AuthorStats',
  tableName: 'author_stats_view',
  view: true,
  expression: `
    select a.name, count(b.id) as book_count
    from author a
    left join book b on b.author_id = a.id
    group by a.id, a.name
  `,
  properties: {
    name: p.string().primary(),
    bookCount: p.integer(),
  },
});
./entities/AuthorStats.ts
@Entity({
  tableName: 'author_stats_view',
  view: true,
  expression: `
    select a.name, count(b.id) as book_count
    from author a
    left join book b on b.author_id = a.id
    group by a.id, a.name
  `,
})
export class AuthorStats {

  @PrimaryKey()
  name!: string;

  @Property()
  bookCount!: number;

}
./entities/AuthorStats.ts
@Entity({
  tableName: 'author_stats_view',
  view: true,
  expression: `
    select a.name, count(b.id) as book_count
    from author a
    left join book b on b.author_id = a.id
    group by a.id, a.name
  `,
})
export class AuthorStats {

  @PrimaryKey()
  name!: string;

  @Property()
  bookCount!: number;

}

使用 QueryBuilder 表达式

你也可以使用返回 QueryBuilder 的回调,以获得类型安全的视图定义:

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

const BookSummarySchema = defineEntity({
  name: 'BookSummary',
  tableName: 'book_summary_view',
  view: true,
  expression: (em: EntityManager) => {
    return em.createQueryBuilder(Book, 'b')
      .select(['b.title', 'a.name as author_name'])
      .join('b.author', 'a');
  },
  properties: {
    title: p.string().primary(),
    authorName: p.string(),
  },
});

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

export const BookSummary = defineEntity({
  name: 'BookSummary',
  tableName: 'book_summary_view',
  view: true,
  expression: (em: EntityManager) => {
    return em.createQueryBuilder(Book, 'b')
      .select(['b.title', 'a.name as author_name'])
      .join('b.author', 'a');
  },
  properties: {
    title: p.string().primary(),
    authorName: p.string(),
  },
});
./entities/BookSummary.ts
@Entity({
  tableName: 'book_summary_view',
  view: true,
  expression: (em: EntityManager) => {
    return em.createQueryBuilder(Book, 'b')
      .select(['b.title', 'a.name as author_name'])
      .join('b.author', 'a');
  },
})
export class BookSummary {

  @PrimaryKey()
  title!: string;

  @Property()
  authorName!: string;

}
./entities/BookSummary.ts
@Entity({
  tableName: 'book_summary_view',
  view: true,
  expression: (em: EntityManager) => {
    return em.createQueryBuilder(Book, 'b')
      .select(['b.title', 'a.name as author_name'])
      .join('b.author', 'a');
  },
})
export class BookSummary {

  @PrimaryKey()
  title!: string;

  @Property()
  authorName!: string;

}

查询视图实体

视图实体可以像任何其他实体一样被查询:

// 查找全部
const stats = await em.find(AuthorStats, {});

// 带条件查找
const prolificAuthors = await em.find(AuthorStats, {
  bookCount: { $gte: 5 },
});

// 使用 QueryBuilder
const topAuthors = await em.createQueryBuilder(AuthorStats, 'a')
  .where({ bookCount: { $gt: 0 } })
  .orderBy({ bookCount: 'desc' })
  .limit(10)
  .getResult();

只读行为

视图实体会被自动标记为只读。尝试持久化对视图实体的修改不会有任何效果:

const stat = await em.findOne(AuthorStats, { name: 'John' });
stat.bookCount = 100; // 该修改不会被持久化
await em.flush(); // 不会为视图实体生成 INSERT/UPDATE

主键

与虚拟实体不同,视图实体可以(并且应该)拥有主键。这带来了:

  • 在一次请求内进行正确的标识映射追踪
  • 使用 findOne 按主键查找
  • (如有需要)在关联中引用视图实体
@Entity({ tableName: 'my_view', view: true, expression: '...' })
export class MyView {
  @PrimaryKey()
  id!: number; // 允许使用主键

  @Property()
  value!: string;
}

使用场景

视图实体非常适合:

  1. 报表查询:为仪表盘预聚合数据
  2. 遗留数据库视图:把已有的数据库视图映射为实体
  3. 复杂连接:简化对经常需要连接的数据的访问
  4. 反规范化数据:为规范化表提供扁平化视图
  5. 访问控制:通过视图暴露有限的数据

受支持的数据库

所有 SQL 数据库都支持视图实体:

  • PostgreSQL
  • MySQL / MariaDB
  • SQLite
  • Microsoft SQL Server

注意:MongoDB 不支持视图实体,因为它没有数据库视图的概念。在 MongoDB 上请改用虚拟实体。

物化视图

物化视图是一项数据库特性,它允许你预先计算查询结果并把它存储在一张表中。

MikroORM 通过设置 view: { materialized: true },在 PostgreSQL 中通过视图实体支持物化视图:

@Entity({
  tableName: 'author_stats_mat_view',
  view: { materialized: true },
  expression: `
    select a.name, count(b.id) as book_count
    from author a
    left join book b on b.author_id = a.id
    group by a.id, a.name
  `,
})
export class AuthorStatsMatView {
  @PrimaryKey()
  name!: string;

  @Property()
  bookCount!: number;
}

关于物化视图的更多内容,请阅读其专门章节。

限制

  • 视图实体是只读的,无法被持久化。
  • 某些数据库对可更新视图可能有限制。