# 视图实体

> 英文标题：View Entities
> 官网原文：https://typeorm.io/docs/entity/view-entities
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 41 块

---

<!-- EN -->
# View Entities

<!-- ZH -->
# 视图实体

<!-- EN -->
## What is a ViewEntity?

<!-- ZH -->
## 什么是 ViewEntity？

<!-- EN -->
View entity is a class that maps to a database view. You can create a view entity by defining a new class and mark it with `@ViewEntity()`:

<!-- ZH -->
视图实体是一个映射到数据库视图的类。你可以通过定义一个新类并用 `@ViewEntity()` 标记它来创建视图实体：

<!-- EN -->
`@ViewEntity()` accepts following options:

<!-- ZH -->
`@ViewEntity()` 接受以下选项：

<!-- EN -->
* `name` - view name. If not specified, then view name is generated from entity class name.
* `database` - database name in selected DB server.
* `schema` - schema name.
* `expression` - view definition. **Required parameter**.
* `dependsOn` - List of other views on which the current views depends. If your view uses another view in its definition, you can add it here so that [migrations](https://typeorm.io/docs/migrations/why) are generated in the correct order.

<!-- ZH -->
* `name` - 视图名称。如果不指定，视图名称会由实体类名生成。
* `database` - 所选数据库服务器中的数据库名。
* `schema` - 模式名。
* `expression` - 视图定义。**必填参数**。
* `dependsOn` - 当前视图所依赖的其他视图列表。如果你的视图在定义中用到了另一个视图，可以把它加在这里，这样[迁移](https://typeorm.io/docs/migrations/why)就会按正确顺序生成。

<!-- EN -->
`expression` can be string with properly escaped columns and tables, depend on database used (postgres in example):

<!-- ZH -->
`expression` 可以是一个字符串，其中的列和表已按所用数据库正确转义（示例中为 postgres）：

<!-- EN -->
```typescript
@ViewEntity({
    expression: `
        SELECT "post"."id" AS "id", "post"."name" AS "name", "category"."name" AS "categoryName"
        FROM "post" "post"
        LEFT JOIN "category" "category" ON "post"."categoryId" = "category"."id"
    `
})
```

<!-- ZH -->
```typescript
@ViewEntity({
    expression: `
        SELECT "post"."id" AS "id", "post"."name" AS "name", "category"."name" AS "categoryName"
        FROM "post" "post"
        LEFT JOIN "category" "category" ON "post"."categoryId" = "category"."id"
    `
})
```

<!-- EN -->
or an instance of QueryBuilder

<!-- ZH -->
也可以是一个 QueryBuilder 实例

<!-- EN -->
```typescript
@ViewEntity({
    expression: (dataSource: DataSource) => dataSource
        .createQueryBuilder()
        .select("post.id", "id")
        .addSelect("post.name", "name")
        .addSelect("category.name", "categoryName")
        .from(Post, "post")
        .leftJoin(Category, "category", "category.id = post.categoryId")
})
```

<!-- ZH -->
```typescript
@ViewEntity({
    expression: (dataSource: DataSource) => dataSource
        .createQueryBuilder()
        .select("post.id", "id")
        .addSelect("post.name", "name")
        .addSelect("category.name", "categoryName")
        .from(Post, "post")
        .leftJoin(Category, "category", "category.id = post.categoryId")
})
```

<!-- EN -->
**Note:** parameter binding is not supported due to drivers limitations. Use the literal parameters instead.

<!-- ZH -->
**注意：** 受驱动限制，不支持参数绑定。请改用字面量参数。

<!-- EN -->
```typescript
@ViewEntity({
    expression: (dataSource: DataSource) => dataSource
        .createQueryBuilder()
        .select("post.id", "id")
        .addSelect("post.name", "name")
        .addSelect("category.name", "categoryName")
        .from(Post, "post")
        .leftJoin(Category, "category", "category.id = post.categoryId")
        .where("category.name = :name", { name: "Cars" })  // <-- this is wrong
        .where("category.name = 'Cars'")                   // <-- and this is right
})
```

<!-- ZH -->
```typescript
@ViewEntity({
    expression: (dataSource: DataSource) => dataSource
        .createQueryBuilder()
        .select("post.id", "id")
        .addSelect("post.name", "name")
        .addSelect("category.name", "categoryName")
        .from(Post, "post")
        .leftJoin(Category, "category", "category.id = post.categoryId")
        .where("category.name = :name", { name: "Cars" })  // <-- 这是错的
        .where("category.name = 'Cars'")                   // <-- 这才是对的
})
```

<!-- EN -->
Each view entity must be registered in your data source options:

<!-- ZH -->
每个视图实体都必须在数据源选项中注册：

<!-- EN -->
```typescript
import { DataSource } from "typeorm"
import { UserView } from "./entities/UserView"

const dataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "test",
    password: "test",
    database: "test",
    entities: [UserView],
})
```

<!-- ZH -->
```typescript
import { DataSource } from "typeorm"
import { UserView } from "./entities/UserView"

const dataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "test",
    password: "test",
    database: "test",
    entities: [UserView],
})
```

<!-- EN -->
## View Entity columns

<!-- ZH -->
## 视图实体列

<!-- EN -->
To map data from view into the correct entity columns you must mark entity columns with `@ViewColumn()` decorator and specify these columns as select statement aliases.

<!-- ZH -->
要把视图中的数据映射到正确的实体列，你必须用 `@ViewColumn()` 装饰器标记实体列，并在 select 语句中把这些列指定为别名。

<!-- EN -->
example with string expression definition:

<!-- ZH -->
使用字符串表达式定义的示例：

<!-- EN -->
```typescript
import { ViewEntity, ViewColumn } from "typeorm"

@ViewEntity({
    expression: `
        SELECT "post"."id" AS "id", "post"."name" AS "name", "category"."name" AS "categoryName"
        FROM "post" "post"
        LEFT JOIN "category" "category" ON "post"."categoryId" = "category"."id"
    `,
})
export class PostCategory {
    @ViewColumn()
    id: number

    @ViewColumn()
    name: string

    @ViewColumn()
    categoryName: string
}
```

<!-- ZH -->
```typescript
import { ViewEntity, ViewColumn } from "typeorm"

@ViewEntity({
    expression: `
        SELECT "post"."id" AS "id", "post"."name" AS "name", "category"."name" AS "categoryName"
        FROM "post" "post"
        LEFT JOIN "category" "category" ON "post"."categoryId" = "category"."id"
    `,
})
export class PostCategory {
    @ViewColumn()
    id: number

    @ViewColumn()
    name: string

    @ViewColumn()
    categoryName: string
}
```

<!-- EN -->
example using QueryBuilder:

<!-- ZH -->
使用 QueryBuilder 的示例：

<!-- EN -->
```typescript
import { ViewEntity, ViewColumn } from "typeorm"

@ViewEntity({
    expression: (dataSource: DataSource) =>
        dataSource
            .createQueryBuilder()
            .select("post.id", "id")
            .addSelect("post.name", "name")
            .addSelect("category.name", "categoryName")
            .from(Post, "post")
            .leftJoin(Category, "category", "category.id = post.categoryId"),
})
export class PostCategory {
    @ViewColumn()
    id: number

    @ViewColumn()
    name: string

    @ViewColumn()
    categoryName: string
}
```

<!-- ZH -->
```typescript
import { ViewEntity, ViewColumn } from "typeorm"

@ViewEntity({
    expression: (dataSource: DataSource) =>
        dataSource
            .createQueryBuilder()
            .select("post.id", "id")
            .addSelect("post.name", "name")
            .addSelect("category.name", "categoryName")
            .from(Post, "post")
            .leftJoin(Category, "category", "category.id = post.categoryId"),
})
export class PostCategory {
    @ViewColumn()
    id: number

    @ViewColumn()
    name: string

    @ViewColumn()
    categoryName: string
}
```

<!-- EN -->
## View Column options

<!-- ZH -->
## 视图列选项

<!-- EN -->
View Column options define additional options for your view entity columns, similar to [column options](https://typeorm.io/docs/entity/entities#column-options) for regular entities.

<!-- ZH -->
视图列选项为你的视图实体列定义额外选项，类似于普通实体的[列选项](https://typeorm.io/docs/entity/entities#column-options)。

<!-- EN -->
You can specify view column options in `@ViewColumn`:

<!-- ZH -->
你可以在 `@ViewColumn` 中指定视图列选项：

<!-- EN -->
```typescript
@ViewColumn({
    name: "postName",
    // ...
})
name: string;
```

<!-- ZH -->
```typescript
@ViewColumn({
    name: "postName",
    // ...
})
name: string;
```

<!-- EN -->
List of available options in `ViewColumnOptions`:

<!-- ZH -->
`ViewColumnOptions` 中可用的选项列表：

<!-- EN -->
* `name: string` - Column name in the database view.
* `transformer: { from(value: DatabaseType): EntityType, to(value: EntityType): DatabaseType }` - Used to unmarshal properties of arbitrary type `DatabaseType` supported by the database into a type `EntityType`. Arrays of transformers are also supported and are applied in reverse order when reading. Note that because database views are read-only, `transformer.to(value)` will never be used.

<!-- ZH -->
* `name: string` - 数据库视图中的列名。
* `transformer: { from(value: DatabaseType): EntityType, to(value: EntityType): DatabaseType }` - 用于把数据库所支持的任意类型 `DatabaseType` 的属性反编组为 `EntityType` 类型。也支持转换器数组，读取时按相反顺序应用。注意，由于数据库视图是只读的，`transformer.to(value)` 永远不会被使用。

<!-- EN -->
## Materialized View Indexes

<!-- ZH -->
## 物化视图索引

<!-- EN -->
There's support for creation of indexes for materialized views if using `PostgreSQL`.

<!-- ZH -->
如果使用 `PostgreSQL`，支持为物化视图创建索引。

<!-- EN -->
```typescript
@ViewEntity({
    materialized: true,
    expression: (dataSource: DataSource) =>
        dataSource
            .createQueryBuilder()
            .select("post.id", "id")
            .addSelect("post.name", "name")
            .addSelect("category.name", "categoryName")
            .from(Post, "post")
            .leftJoin(Category, "category", "category.id = post.categoryId"),
})
export class PostCategory {
    @ViewColumn()
    id: number

    @Index()
    @ViewColumn()
    name: string

    @Index("catname-idx")
    @ViewColumn()
    categoryName: string
}
```

<!-- ZH -->
```typescript
@ViewEntity({
    materialized: true,
    expression: (dataSource: DataSource) =>
        dataSource
            .createQueryBuilder()
            .select("post.id", "id")
            .addSelect("post.name", "name")
            .addSelect("category.name", "categoryName")
            .from(Post, "post")
            .leftJoin(Category, "category", "category.id = post.categoryId"),
})
export class PostCategory {
    @ViewColumn()
    id: number

    @Index()
    @ViewColumn()
    name: string

    @Index("catname-idx")
    @ViewColumn()
    categoryName: string
}
```

<!-- EN -->
However, `unique` is currently the only supported option for indexes in materialized views. The rest of the index options will be ignored.

<!-- ZH -->
不过，`unique` 目前是物化视图索引唯一受支持的选项。其余索引选项都会被忽略。

<!-- EN -->
```typescript
@Index("name-idx", { unique: true })
@ViewColumn()
name: string
```

<!-- ZH -->
```typescript
@Index("name-idx", { unique: true })
@ViewColumn()
name: string
```

<!-- EN -->
## Complete example

<!-- ZH -->
## 完整示例

<!-- EN -->
Lets create two entities and a view containing aggregated data from these entities:

<!-- ZH -->
我们来创建两个实体，以及一个包含这两个实体聚合数据的视图：

<!-- EN -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity()
export class Category {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string
}
```

<!-- ZH -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity()
export class Category {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string
}
```

<!-- EN -->
```typescript
import {
    Entity,
    PrimaryGeneratedColumn,
    Column,
    ManyToOne,
    JoinColumn,
} from "typeorm"
import { Category } from "./Category"

@Entity()
export class Post {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @Column()
    categoryId: number

    @ManyToOne(() => Category)
    @JoinColumn({ name: "categoryId" })
    category: Category
}
```

<!-- ZH -->
```typescript
import {
    Entity,
    PrimaryGeneratedColumn,
    Column,
    ManyToOne,
    JoinColumn,
} from "typeorm"
import { Category } from "./Category"

@Entity()
export class Post {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @Column()
    categoryId: number

    @ManyToOne(() => Category)
    @JoinColumn({ name: "categoryId" })
    category: Category
}
```

<!-- EN -->
```typescript
import { ViewEntity, ViewColumn, DataSource } from "typeorm"

@ViewEntity({
    expression: (dataSource: DataSource) =>
        dataSource
            .createQueryBuilder()
            .select("post.id", "id")
            .addSelect("post.name", "name")
            .addSelect("category.name", "categoryName")
            .from(Post, "post")
            .leftJoin(Category, "category", "category.id = post.categoryId"),
})
export class PostCategory {
    @ViewColumn()
    id: number

    @ViewColumn()
    name: string

    @ViewColumn()
    categoryName: string
}
```

<!-- ZH -->
```typescript
import { ViewEntity, ViewColumn, DataSource } from "typeorm"

@ViewEntity({
    expression: (dataSource: DataSource) =>
        dataSource
            .createQueryBuilder()
            .select("post.id", "id")
            .addSelect("post.name", "name")
            .addSelect("category.name", "categoryName")
            .from(Post, "post")
            .leftJoin(Category, "category", "category.id = post.categoryId"),
})
export class PostCategory {
    @ViewColumn()
    id: number

    @ViewColumn()
    name: string

    @ViewColumn()
    categoryName: string
}
```

<!-- EN -->
then fill these tables with data and request all data from PostCategory view:

<!-- ZH -->
然后往这些表里填充数据，并从 PostCategory 视图中查询所有数据：

<!-- EN -->
```typescript
import { Category } from "./entities/Category"
import { Post } from "./entities/Post"
import { PostCategory } from "./entities/PostCategory"

const category1 = new Category()
category1.name = "Cars"
await dataSource.manager.save(category1)

const category2 = new Category()
category2.name = "Airplanes"
await dataSource.manager.save(category2)

const post1 = new Post()
post1.name = "About BMW"
post1.categoryId = category1.id
await dataSource.manager.save(post1)

const post2 = new Post()
post2.name = "About Boeing"
post2.categoryId = category2.id
await dataSource.manager.save(post2)

const postCategories = await dataSource.manager.find(PostCategory)
const postCategory = await dataSource.manager.findOneBy(PostCategory, { id: 1 })
```

<!-- ZH -->
```typescript
import { Category } from "./entities/Category"
import { Post } from "./entities/Post"
import { PostCategory } from "./entities/PostCategory"

const category1 = new Category()
category1.name = "Cars"
await dataSource.manager.save(category1)

const category2 = new Category()
category2.name = "Airplanes"
await dataSource.manager.save(category2)

const post1 = new Post()
post1.name = "About BMW"
post1.categoryId = category1.id
await dataSource.manager.save(post1)

const post2 = new Post()
post2.name = "About Boeing"
post2.categoryId = category2.id
await dataSource.manager.save(post2)

const postCategories = await dataSource.manager.find(PostCategory)
const postCategory = await dataSource.manager.findOneBy(PostCategory, { id: 1 })
```

<!-- EN -->
the result in `postCategories` will be:

<!-- ZH -->
`postCategories` 中的结果将是：

<!-- EN -->
```javascript
[ PostCategory { id: 1, name: 'About BMW', categoryName: 'Cars' },
  PostCategory { id: 2, name: 'About Boeing', categoryName: 'Airplanes' } ]
```

<!-- ZH -->
```javascript
[ PostCategory { id: 1, name: 'About BMW', categoryName: 'Cars' },
  PostCategory { id: 2, name: 'About Boeing', categoryName: 'Airplanes' } ]
```

<!-- EN -->
and in `postCategory`:

<!-- ZH -->
而 `postCategory` 中是：

<!-- EN -->
```javascript
PostCategory { id: 1, name: 'About BMW', categoryName: 'Cars' }
```

<!-- ZH -->
```javascript
PostCategory { id: 1, name: 'About BMW', categoryName: 'Cars' }
```
