---
title: 视图实体
---

来源：https://mikro-orm.io/docs/view-entities

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

视图实体代表由 MikroORM 的 schema 生成器创建并管理的真实数据库视图。与在查询时求值表达式的[虚拟实体](./42-virtual-entities.md)不同，视图实体会在你的数据库中创建持久的 `CREATE VIEW` 语句。

<a id="virtual-entities-vs-view-entities"></a>
## 虚拟实体与视图实体对比

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

<a id="defining-view-entities"></a>
## 定义视图实体

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

<a id="using-string-expression"></a>
### 使用字符串表达式

<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/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);
```

  </TabItem>

  <TabItem value="define-entity">

```ts title="./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(),
  },
});
```

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

```ts title="./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;

}
```

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

```ts title="./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;

}
```

  </TabItem>
</Tabs>

<a id="using-querybuilder-expression"></a>
### 使用 QueryBuilder 表达式

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

<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/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);
```

  </TabItem>

  <TabItem value="define-entity">

```ts title="./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(),
  },
});
```

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

```ts title="./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;

}
```

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

```ts title="./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;

}
```

  </TabItem>
</Tabs>

<a id="querying-view-entities"></a>
## 查询视图实体

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

```ts
// 查找全部
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();
```

<a id="read-only-behavior"></a>
## 只读行为

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

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

<a id="primary-keys"></a>
## 主键

与虚拟实体不同，视图实体可以（并且应该）拥有主键。这带来了：

- 在一次请求内进行正确的标识映射追踪
- 使用 `findOne` 按主键查找
- （如有需要）在关联中引用视图实体

```ts
@Entity({ tableName: 'my_view', view: true, expression: '...' })
export class MyView {
  @PrimaryKey()
  id!: number; // 允许使用主键

  @Property()
  value!: string;
}
```

<a id="use-cases"></a>
## 使用场景

视图实体非常适合：

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

<a id="supported-databases"></a>
## 受支持的数据库

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

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

> 注意：MongoDB 不支持视图实体，因为它没有数据库视图的概念。在 MongoDB 上请改用[虚拟实体](./42-virtual-entities.md)。

<a id="materialized-views"></a>
## 物化视图

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

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

```ts
@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;
}
```

关于物化视图的更多内容，请阅读[其专门章节](./44-materialized-views.md)。

<a id="limitations"></a>
## 限制

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