# 装饰器参考

> 英文标题：Decorator reference
> 官网原文：https://typeorm.io/docs/help/decorator-reference
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 190 块

---

<!-- EN -->
# Decorator reference

<!-- ZH -->
# 装饰器参考

<!-- EN -->
## Entity decorators

<!-- ZH -->
## 实体装饰器

<!-- EN -->
#### `@Entity`

<!-- ZH -->
#### `@Entity`

<!-- EN -->
Marks your model as an entity. Entity is a class which is transformed into a database table. You can specify the table name in the entity:

<!-- ZH -->
把你的模型标记为实体。实体是一个会被转换成数据库表的类。你可以在实体中指定表名：

<!-- EN -->
```typescript
@Entity("users")
export class User {}
```

<!-- ZH -->
```typescript
@Entity("users")
export class User {}
```

<!-- EN -->
This code will create a database table named "users".

<!-- ZH -->
这段代码会创建一张名为 "users" 的数据库表。

<!-- EN -->
You can also specify some additional entity options:

<!-- ZH -->
你也可以指定一些额外的实体选项：

<!-- EN -->
* `name` - table name. If not specified, then table name is generated from entity class name.
* `database` - database name in selected DB server.
* `schema` - schema name.
* `comment` - Database table comment. Not supported by all database types. Currently supported by MySQL, MariaDB, PostgreSQL, SAP HANA.
* `engine` - database engine to be set during table creation (works only in some databases).
* `synchronize` - entities marked with `false` are skipped from schema updates.
* `orderBy` - specifies default ordering for entities when using `find` operations and `QueryBuilder`.

<!-- ZH -->
* `name` - 表名。如果不指定，表名会由实体类名生成。
* `database` - 所选数据库服务器中的数据库名。
* `schema` - 模式名。
* `comment` - 数据库表注释。并非所有数据库类型都支持。目前 MySQL、MariaDB、PostgreSQL、SAP HANA 支持。
* `engine` - 建表时要设置的数据库引擎（仅在部分数据库中有效）。
* `synchronize` - 用 `false` 标记的实体会在结构更新中被跳过。
* `orderBy` - 指定使用 `find` 操作和 `QueryBuilder` 时实体的默认排序。

<!-- EN -->
Example:

<!-- ZH -->
示例：

<!-- EN -->
```typescript
@Entity({
    name: "users",
    engine: "MyISAM",
    database: "example_dev",
    schema: "schema_with_best_tables",
    comment: "This is users table",
    synchronize: false,
    orderBy: {
        name: "ASC",
        id: "DESC",
    },
})
export class User {}
```

<!-- ZH -->
```typescript
@Entity({
    name: "users",
    engine: "MyISAM",
    database: "example_dev",
    schema: "schema_with_best_tables",
    comment: "This is users table",
    synchronize: false,
    orderBy: {
        name: "ASC",
        id: "DESC",
    },
})
export class User {}
```

<!-- EN -->
Learn more about [Entities](https://typeorm.io/docs/entity/entities).

<!-- ZH -->
进一步了解[实体](https://typeorm.io/docs/entity/entities)。

<!-- EN -->
#### `@ViewEntity`

<!-- ZH -->
#### `@ViewEntity`

<!-- EN -->
View entity is a class that maps to a database view.

<!-- ZH -->
视图实体是一个映射到数据库视图的类。

<!-- 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**.

<!-- ZH -->
* `name` - 视图名称。如果不指定，视图名称会由实体类名生成。
* `database` - 所选数据库服务器中的数据库名。
* `schema` - 模式名。
* `expression` - 视图定义。**必填参数**。

<!-- 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" "id", "post"."name" AS "name", "category"."name" AS "categoryName"
        FROM "post" "post"
        LEFT JOIN "category" "category" ON "post"."categoryId" = "category"."id"
    `,
})
export class PostCategory {}
```

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

<!-- 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"),
})
export class PostCategory {}
```

<!-- 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"),
})
export class PostCategory {}
```

<!-- 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
})
export class PostCategory {}
```

<!-- 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'"), // <-- 这才是对的
})
export class PostCategory {}
```

<!-- EN -->
Learn more about [View Entities](https://typeorm.io/docs/entity/view-entities).

<!-- ZH -->
进一步了解[视图实体](https://typeorm.io/docs/entity/view-entities)。

<!-- EN -->
## Column decorators

<!-- ZH -->
## 列装饰器

<!-- EN -->
#### `@Column`

<!-- ZH -->
#### `@Column`

<!-- EN -->
Marks a property in your entity as a table column. Example:

<!-- ZH -->
把你实体中的一个属性标记为表列。示例：

<!-- EN -->
```typescript
@Entity("users")
export class User {
    @Column({ primary: true })
    id: number

    @Column({ type: "varchar", length: 200, unique: true })
    firstName: string

    @Column({ nullable: true })
    lastName: string

    @Column({ default: false })
    isActive: boolean
}
```

<!-- ZH -->
```typescript
@Entity("users")
export class User {
    @Column({ primary: true })
    id: number

    @Column({ type: "varchar", length: 200, unique: true })
    firstName: string

    @Column({ nullable: true })
    lastName: string

    @Column({ default: false })
    isActive: boolean
}
```

<!-- EN -->
`@Column` accept several options you can use:

<!-- ZH -->
`@Column` 接受若干你可以使用的选项：

<!-- EN -->
* `type: ColumnType` - Column type. One of the [supported column types](https://typeorm.io/docs/entity/entities#column-types).
* `name: string` - Column name in the database table. By default, the column name is generated from the name of the property. You can change it by specifying your own name.
* `length: string|number` - Column type's length. For example, if you want to create `varchar(150)` type you specify column type and length options.
* `width: number` - column type's display width. Used only for [MySQL integer types](https://dev.mysql.com/doc/refman/5.7/en/integer-types.html). *Deprecated* in newer MySQL versions, will be removed from TypeORM in an upcoming version.
* `onUpdate: string` - `ON UPDATE` trigger. Used only in [MySQL](https://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html).
* `nullable: boolean` - determines whether the column can become `NULL` or always has to be `NOT NULL`. By default column is `nullable: false`.
* `update: boolean` - Indicates if column value is updated by "save" operation. If false, you'll be able to write this value only when you first time insert the object. Default value is `true`.
* `insert: boolean` - Indicates if column value is set the first time you insert the object. Default value is `true`.
* `select: boolean` - Defines whether or not to hide this column by default when making queries. When set to `false`, the column data will not show with a standard query. By default column is `select: true`
* `default: string` - Adds database-level column's `DEFAULT` value.
* `primary: boolean` - Marks column as primary. Same as using `@PrimaryColumn`.
* `unique: boolean` - Marks column as unique column (creates unique constraint). Default value is false.
* `comment: string` - Database's column comment. Not supported by all database types.
* `precision: number` - The precision for a decimal (exact numeric) column (applies only for decimal column), which is the maximum number of digits that are stored for the values. Used in some column types.
* `scale: number` - The scale for a decimal (exact numeric) column (applies only for decimal column), which represents the number of digits to the right of the decimal point and must not be greater than precision. Used in some column types.
* `zerofill: boolean` - Puts `ZEROFILL` attribute on to a numeric column. Used only in MySQL. If `true`, MySQL automatically adds the `UNSIGNED` attribute to this column. *Deprecated* in newer MySQL versions, will be removed from TypeORM in an upcoming version. Use a character column and the `LPAD` function as suggested by MySQL.
* `unsigned: boolean` - Puts `UNSIGNED` attribute on to a numeric column. Used only in MySQL.
* `charset: string` - Defines a column character set. Not supported by all database types.
* `collation: string` - Defines a column collation.
* `enum: string[]|AnyEnum` - Used in `enum` column type to specify list of allowed enum values. You can specify array of values or specify a enum class.
* `enumName: string` - A name for generated enum type. If not specified, TypeORM will generate a enum type from entity and column names - so it's necessary if you intend to use the same enum type in different tables.
* `primaryKeyConstraintName: string` - A name for the primary key constraint. If not specified, then constraint name is generated from the table name and the names of the involved columns.
* `asExpression: string` - Generated column expression. Supported by PostgreSQL/CockroachDB, MySQL/MariaDB, Oracle, SAP HANA, Spanner, SQLite, and SQL Server.
* `generatedType: "VIRTUAL"|"STORED"` - Generated column type. Supported by PostgreSQL (`STORED` only), CockroachDB, MySQL/MariaDB, Oracle (`VIRTUAL` only), Spanner (`STORED` only), SQLite, and SQL Server (`STORED` only, internally mapped to `PERSISTED`).
* `hstoreType: "object"|"string"` - Return type of `HSTORE` column. Returns value as string or as object. Used only in [Postgres](https://www.postgresql.org/docs/9.6/static/hstore.html).
* `array: boolean` - Used for postgres and cockroachdb column types which can be array (for example int\[]).
* `transformer: ValueTransformer|ValueTransformer[]` - Specifies a value transformer (or array of value transformers) that is to be used to (un)marshal this column when reading or writing to the database. In case of an array, the value transformers will be applied in the natural order from entityValue to databaseValue, and in reverse order from databaseValue to entityValue.
* `spatialFeatureType: string` - Optional feature type (`Point`, `Polygon`, `LineString`, `Geometry`) used as a constraint on a spatial column, optionally with a `Z`, `M` or `ZM` dimensional suffix (`PointZ`, `GeometryZM`). If not specified, it will behave as though `Geometry` was provided. Used only in PostgreSQL and CockroachDB.
* `srid: number` - Optional [Spatial Reference ID](https://postgis.net/docs/using_postgis_dbmanagement.html#spatial_ref_sys) used as a constraint on a spatial column. If not specified, it will default to `0`. Standard geographic coordinates (latitude/longitude in the WGS84 datum) correspond to [EPSG 4326](http://spatialreference.org/ref/epsg/wgs-84/). Used only in PostgreSQL and CockroachDB.

<!-- ZH -->
* `type: ColumnType` - 列类型。[受支持的列类型](https://typeorm.io/docs/entity/entities#column-types)之一。
* `name: string` - 数据库表中的列名。默认情况下，列名由属性名生成。你可以通过指定自己的名称来修改它。
* `length: string|number` - 列类型的长度。例如，如果你想创建 `varchar(150)` 类型，就要指定列类型和 length 选项。
* `width: number` - 列类型的显示宽度。仅用于 [MySQL 整数类型](https://dev.mysql.com/doc/refman/5.7/en/integer-types.html)。在较新的 MySQL 版本中已*弃用*，将在 TypeORM 的后续版本中移除。
* `onUpdate: string` - `ON UPDATE` 触发器。仅在 [MySQL](https://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html) 中使用。
* `nullable: boolean` - 决定该列是否可以变成 `NULL`，还是必须始终是 `NOT NULL`。默认情况下列是 `nullable: false`。
* `update: boolean` - 表示列值是否会被 "save" 操作更新。如果为 false，你只能在首次插入对象时写入该值。默认值为 `true`。
* `insert: boolean` - 表示列值是否在首次插入对象时被设置。默认值为 `true`。
* `select: boolean` - 定义查询时是否默认隐藏该列。设为 `false` 时，标准查询不会返回该列数据。默认情况下列是 `select: true`
* `default: string` - 添加数据库层面的列 `DEFAULT` 值。
* `primary: boolean` - 把列标记为主键。等同于使用 `@PrimaryColumn`。
* `unique: boolean` - 把列标记为唯一列（创建唯一约束）。默认值为 false。
* `comment: string` - 数据库的列注释。并非所有数据库类型都支持。
* `precision: number` - decimal（精确数值）列的精度（仅适用于 decimal 列），即存储数值时的最大位数。用于某些列类型。
* `scale: number` - decimal（精确数值）列的标度（仅适用于 decimal 列），表示小数点右侧的位数，且不能大于 precision。用于某些列类型。
* `zerofill: boolean` - 给数值列加上 `ZEROFILL` 属性。仅在 MySQL 中使用。如果为 `true`，MySQL 会自动给该列加上 `UNSIGNED` 属性。在较新的 MySQL 版本中已*弃用*，将在 TypeORM 的后续版本中移除。请按 MySQL 的建议改用字符列和 `LPAD` 函数。
* `unsigned: boolean` - 给数值列加上 `UNSIGNED` 属性。仅在 MySQL 中使用。
* `charset: string` - 定义列的字符集。并非所有数据库类型都支持。
* `collation: string` - 定义列的排序规则。
* `enum: string[]|AnyEnum` - 在 `enum` 列类型中用于指定允许的枚举值列表。你可以指定值数组，也可以指定一个枚举类。
* `enumName: string` - 生成的枚举类型的名称。如果不指定，TypeORM 会根据实体名和列名生成枚举类型——因此如果你打算在不同表中使用同一个枚举类型，就有必要指定它。
* `primaryKeyConstraintName: string` - 主键约束的名称。如果不指定，约束名会由表名和所涉及列的名称生成。
* `asExpression: string` - 生成列表达式。受 PostgreSQL/CockroachDB、MySQL/MariaDB、Oracle、SAP HANA、Spanner、SQLite 和 SQL Server 支持。
* `generatedType: "VIRTUAL"|"STORED"` - 生成列类型。受 PostgreSQL（仅 `STORED`）、CockroachDB、MySQL/MariaDB、Oracle（仅 `VIRTUAL`）、Spanner（仅 `STORED`）、SQLite 和 SQL Server（仅 `STORED`，内部映射为 `PERSISTED`）支持。
* `hstoreType: "object"|"string"` - `HSTORE` 列的返回类型。以字符串或对象形式返回值。仅在 [Postgres](https://www.postgresql.org/docs/9.6/static/hstore.html) 中使用。
* `array: boolean` - 用于 postgres 和 cockroachdb 中可以为数组的列类型（例如 int\[]）。
* `transformer: ValueTransformer|ValueTransformer[]` - 指定一个值转换器（或值转换器数组），用于在读写数据库时（反）编组该列。如果是数组，值转换器会按从 entityValue 到 databaseValue 的自然顺序应用，并按从 databaseValue 到 entityValue 的相反顺序应用。
* `spatialFeatureType: string` - 可选的要素类型（`Point`、`Polygon`、`LineString`、`Geometry`），用作空间列上的约束，可选地带 `Z`、`M` 或 `ZM` 维度后缀（`PointZ`、`GeometryZM`）。如果不指定，其行为等同于提供了 `Geometry`。仅在 PostgreSQL 和 CockroachDB 中使用。
* `srid: number` - 可选的[空间参考 ID](https://postgis.net/docs/using_postgis_dbmanagement.html#spatial_ref_sys)，用作空间列上的约束。如果不指定，默认为 `0`。标准地理坐标（WGS84 基准下的经纬度）对应 [EPSG 4326](http://spatialreference.org/ref/epsg/wgs-84/)。仅在 PostgreSQL 和 CockroachDB 中使用。

<!-- EN -->
Learn more about [entity columns](https://typeorm.io/docs/entity/entities#entity-columns).

<!-- ZH -->
进一步了解[实体列](https://typeorm.io/docs/entity/entities#entity-columns)。

<!-- EN -->
#### `@PrimaryColumn`

<!-- ZH -->
#### `@PrimaryColumn`

<!-- EN -->
Marks a property in your entity as a table primary column. Same as `@Column` decorator but sets its `primary` option to true.

<!-- ZH -->
把你实体中的一个属性标记为表的主键列。与 `@Column` 装饰器相同，但把它的 `primary` 选项设为 true。

<!-- EN -->
Example:

<!-- ZH -->
示例：

<!-- EN -->
```typescript
@Entity()
export class User {
    @PrimaryColumn()
    id: number
}
```

<!-- ZH -->
```typescript
@Entity()
export class User {
    @PrimaryColumn()
    id: number
}
```

<!-- EN -->
`@PrimaryColumn()` supports custom primary key constraint name:

<!-- ZH -->
`@PrimaryColumn()` 支持自定义主键约束名：

<!-- EN -->
```typescript
@Entity()
export class User {
    @PrimaryColumn({ primaryKeyConstraintName: "pk_user_id" })
    id: number
}
```

<!-- ZH -->
```typescript
@Entity()
export class User {
    @PrimaryColumn({ primaryKeyConstraintName: "pk_user_id" })
    id: number
}
```

<!-- EN -->
> Note: when using `primaryKeyConstraintName` with multiple primary keys, the constraint name must be the same for all primary columns.

<!-- ZH -->
> 注意：把 `primaryKeyConstraintName` 与多个主键一起使用时，所有主键列的约束名必须相同。

<!-- EN -->
Learn more about [entity columns](https://typeorm.io/docs/entity/entities#entity-columns).

<!-- ZH -->
进一步了解[实体列](https://typeorm.io/docs/entity/entities#entity-columns)。

<!-- EN -->
#### `@PrimaryGeneratedColumn`

<!-- ZH -->
#### `@PrimaryGeneratedColumn`

<!-- EN -->
Marks a property in your entity as a table-generated primary column. Column it creates is primary and its value is auto-generated. Example:

<!-- ZH -->
把你实体中的一个属性标记为由表生成的主键列。它创建的列是主键，且其值自动生成。示例：

<!-- EN -->
```typescript
@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number
}
```

<!-- ZH -->
```typescript
@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number
}
```

<!-- EN -->
`@PrimaryGeneratedColumn()` supports custom primary key constraint name:

<!-- ZH -->
`@PrimaryGeneratedColumn()` 支持自定义主键约束名：

<!-- EN -->
```typescript
@Entity()
export class User {
    @PrimaryGeneratedColumn({ primaryKeyConstraintName: "pk_user_id" })
    id: number
}
```

<!-- ZH -->
```typescript
@Entity()
export class User {
    @PrimaryGeneratedColumn({ primaryKeyConstraintName: "pk_user_id" })
    id: number
}
```

<!-- EN -->
There are four generation strategies:

<!-- ZH -->
共有四种生成策略：

<!-- EN -->
* `increment` - uses AUTO_INCREMENT / SERIAL / SEQUENCE (depend on database type) to generate incremental number.

<!-- ZH -->
* `increment` - 使用 AUTO_INCREMENT / SERIAL / SEQUENCE（取决于数据库类型）生成递增数字。

<!-- EN -->
* `identity` - only for [PostgreSQL 10+](https://www.postgresql.org/docs/13/sql-createtable.html). Postgres versions above 10 support the SQL-Compliant **IDENTITY** column. When marking the generation strategy as `identity` the column will be produced using `GENERATED [ALWAYS|BY DEFAULT] AS IDENTITY`

<!-- ZH -->
* `identity` - 仅适用于 [PostgreSQL 10+](https://www.postgresql.org/docs/13/sql-createtable.html)。10 以上的 Postgres 版本支持符合 SQL 标准的 **IDENTITY** 列。当把生成策略标记为 `identity` 时，该列会使用 `GENERATED [ALWAYS|BY DEFAULT] AS IDENTITY` 创建

<!-- EN -->
* `uuid` - generates unique `uuid` string.

<!-- ZH -->
* `uuid` - 生成唯一的 `uuid` 字符串。

<!-- EN -->
* `rowid` - only for [CockroachDB](https://www.cockroachlabs.com/docs/stable/serial.html). Value is automatically generated using the `unique_rowid()` function. This produces a 64-bit integer from the current timestamp and ID of the node executing the `INSERT` or `UPSERT` operation.

<!-- ZH -->
* `rowid` - 仅适用于 [CockroachDB](https://www.cockroachlabs.com/docs/stable/serial.html)。值会使用 `unique_rowid()` 函数自动生成。该函数根据当前时间戳和执行 `INSERT` 或 `UPSERT` 操作的节点 ID 生成一个 64 位整数。

<!-- EN -->
  <!-- -->

<!-- ZH -->
  <!-- -->

<!-- EN -->
  > Note: property with a `rowid` generation strategy must be a `string` data type

<!-- ZH -->
  > 注意：使用 `rowid` 生成策略的属性必须是 `string` 数据类型

<!-- EN -->
Default generation strategy is `increment`, to change it to another strategy, simply pass it as the first argument to decorator:

<!-- ZH -->
默认生成策略是 `increment`，要改成其他策略，只需把它作为第一个参数传给装饰器：

<!-- EN -->
```typescript
@Entity()
export class User {
    @PrimaryGeneratedColumn("uuid")
    id: string
}
```

<!-- ZH -->
```typescript
@Entity()
export class User {
    @PrimaryGeneratedColumn("uuid")
    id: string
}
```

<!-- EN -->
Learn more about [entity columns](https://typeorm.io/docs/entity/entities#entity-columns).

<!-- ZH -->
进一步了解[实体列](https://typeorm.io/docs/entity/entities#entity-columns)。

<!-- EN -->
#### `@ObjectIdColumn`

<!-- ZH -->
#### `@ObjectIdColumn`

<!-- EN -->
Marks a property in your entity as `ObjectId`. This decorator is only used in MongoDB. Every entity in MongoDB must have an `ObjectId` column. Example:

<!-- ZH -->
把你实体中的一个属性标记为 `ObjectId`。该装饰器仅用于 MongoDB。MongoDB 中的每个实体都必须有一个 `ObjectId` 列。示例：

<!-- EN -->
```typescript
@Entity()
export class User {
    @ObjectIdColumn()
    id: ObjectId
}
```

<!-- ZH -->
```typescript
@Entity()
export class User {
    @ObjectIdColumn()
    id: ObjectId
}
```

<!-- EN -->
Learn more about [MongoDB](https://typeorm.io/docs/drivers/mongodb).

<!-- ZH -->
进一步了解 [MongoDB](https://typeorm.io/docs/drivers/mongodb)。

<!-- EN -->
#### `@CreateDateColumn`

<!-- ZH -->
#### `@CreateDateColumn`

<!-- EN -->
Special column that is automatically set to the entity's insertion time. You don't need to write a value into this column - it will be automatically set. Example:

<!-- ZH -->
特殊列，会被自动设置为实体的插入时间。你不需要往这一列里写值——它会被自动设置。示例：

<!-- EN -->
```typescript
@Entity()
export class User {
    @CreateDateColumn()
    createdDate: Date
}
```

<!-- ZH -->
```typescript
@Entity()
export class User {
    @CreateDateColumn()
    createdDate: Date
}
```

<!-- EN -->
#### `@UpdateDateColumn`

<!-- ZH -->
#### `@UpdateDateColumn`

<!-- EN -->
Special column that is automatically set to the entity's update time each time you call `save` from entity manager or repository. You don't need to write a value into this column - it will be automatically set.

<!-- ZH -->
特殊列，每次你调用 entity manager 或 repository 的 `save` 时，它都会被自动设置为实体的更新时间。你不需要往这一列里写值——它会被自动设置。

<!-- EN -->
This column is also automatically updated during `upsert` operations when an update occurs due to a conflict.

<!-- ZH -->
当 `upsert` 操作因冲突而发生更新时，这一列也会被自动更新。

<!-- EN -->
```typescript
@Entity()
export class User {
    @UpdateDateColumn()
    updatedDate: Date
}
```

<!-- ZH -->
```typescript
@Entity()
export class User {
    @UpdateDateColumn()
    updatedDate: Date
}
```

<!-- EN -->
#### `@DeleteDateColumn`

<!-- ZH -->
#### `@DeleteDateColumn`

<!-- EN -->
Special column that is automatically set to the entity's delete time each time you call soft-delete of entity manager or repository. You don't need to set this column - it will be automatically set.

<!-- ZH -->
特殊列，每次你调用 entity manager 或 repository 的软删除时，它都会被自动设置为实体的删除时间。你不需要设置这一列——它会被自动设置。

<!-- EN -->
TypeORM's own soft delete functionality utilizes global scopes to only pull "non-deleted" entities from the database.

<!-- ZH -->
TypeORM 自身的软删除功能利用全局作用域，只从数据库中取出"未删除"的实体。

<!-- EN -->
If the @DeleteDateColumn is set, the default scope will be "non-deleted".

<!-- ZH -->
如果设置了 @DeleteDateColumn，默认作用域将是"未删除"。

<!-- EN -->
```typescript
@Entity()
export class User {
    @DeleteDateColumn()
    deletedDate: Date
}
```

<!-- ZH -->
```typescript
@Entity()
export class User {
    @DeleteDateColumn()
    deletedDate: Date
}
```

<!-- EN -->
#### `@VersionColumn`

<!-- ZH -->
#### `@VersionColumn`

<!-- EN -->
Special column that is automatically set to the entity's version (incremental number) each time you call `save` from entity manager or repository. You don't need to write a value into this column - it will be automatically set.

<!-- ZH -->
特殊列，每次你调用 entity manager 或 repository 的 `save` 时，它都会被自动设置为实体的版本号（递增数字）。你不需要往这一列里写值——它会被自动设置。

<!-- EN -->
This column is also automatically updated during `upsert` operations when an update occurs due to a conflict.

<!-- ZH -->
当 `upsert` 操作因冲突而发生更新时，这一列也会被自动更新。

<!-- EN -->
```typescript
@Entity()
export class User {
    @VersionColumn()
    version: number
}
```

<!-- ZH -->
```typescript
@Entity()
export class User {
    @VersionColumn()
    version: number
}
```

<!-- EN -->
#### `@Generated`

<!-- ZH -->
#### `@Generated`

<!-- EN -->
Marks column to be a generated value. For example:

<!-- ZH -->
把列标记为生成值。例如：

<!-- EN -->
```typescript
@Entity()
export class User {
    @Column()
    @Generated("uuid")
    uuid: string
}
```

<!-- ZH -->
```typescript
@Entity()
export class User {
    @Column()
    @Generated("uuid")
    uuid: string
}
```

<!-- EN -->
Value will be generated only once, before inserting the entity into the database.

<!-- ZH -->
值只会生成一次，在把实体插入数据库之前。

<!-- EN -->
#### `@VirtualColumn`

<!-- ZH -->
#### `@VirtualColumn`

<!-- EN -->
Special column that is never saved to the database and thus acts as a readonly property. Each time you call `find` or `findOne` from the entity manager, the value is recalculated based on the query function that was provided in the VirtualColumn Decorator. The alias argument passed to the query references the exact entity alias of the generated query behind the scenes.

<!-- ZH -->
特殊列，它永远不会被保存到数据库，因此表现得像只读属性。每次你调用 entity manager 的 `find` 或 `findOne` 时，该值都会根据 VirtualColumn 装饰器中提供的查询函数重新计算。传给查询的 alias 参数引用的是幕后所生成查询中该实体的确切别名。

<!-- EN -->
```typescript
@Entity({ name: "companies", alias: "COMP" })
export class Company extends BaseEntity {
    @PrimaryColumn("varchar", { length: 50 })
    name: string

    @VirtualColumn({
        query: (alias) =>
            `SELECT COUNT("name") FROM "employees" WHERE "companyName" = ${alias}.name`,
    })
    totalEmployeesCount: number

    @OneToMany((type) => Employee, (employee) => employee.company)
    employees: Employee[]
}

@Entity({ name: "employees" })
export class Employee extends BaseEntity {
    @PrimaryColumn("varchar", { length: 50 })
    name: string

    @ManyToOne((type) => Company, (company) => company.employees)
    company: Company
}
```

<!-- ZH -->
```typescript
@Entity({ name: "companies", alias: "COMP" })
export class Company extends BaseEntity {
    @PrimaryColumn("varchar", { length: 50 })
    name: string

    @VirtualColumn({
        query: (alias) =>
            `SELECT COUNT("name") FROM "employees" WHERE "companyName" = ${alias}.name`,
    })
    totalEmployeesCount: number

    @OneToMany((type) => Employee, (employee) => employee.company)
    employees: Employee[]
}

@Entity({ name: "employees" })
export class Employee extends BaseEntity {
    @PrimaryColumn("varchar", { length: 50 })
    name: string

    @ManyToOne((type) => Company, (company) => company.employees)
    company: Company
}
```

<!-- EN -->
## Relation decorators

<!-- ZH -->
## 关系装饰器

<!-- EN -->
#### `@OneToOne`

<!-- ZH -->
#### `@OneToOne`

<!-- EN -->
One-to-one is a relation where A contains only one instance of B, and B contains only one instance of A. Let's take for example `User` and `Profile` entities. User can have only a single profile, and a single profile is owned by only a single user. Example:

<!-- ZH -->
一对一是一种 A 只包含一个 B 实例、且 B 只包含一个 A 实例的关系。以 `User` 和 `Profile` 实体为例。一个用户只能有一个档案，而一个档案只属于一个用户。示例：

<!-- EN -->
```typescript
import { Entity, OneToOne, JoinColumn } from "typeorm"
import { Profile } from "./Profile"

@Entity()
export class User {
    @OneToOne((type) => Profile, (profile) => profile.user)
    @JoinColumn()
    profile: Profile
}
```

<!-- ZH -->
```typescript
import { Entity, OneToOne, JoinColumn } from "typeorm"
import { Profile } from "./Profile"

@Entity()
export class User {
    @OneToOne((type) => Profile, (profile) => profile.user)
    @JoinColumn()
    profile: Profile
}
```

<!-- EN -->
Learn more about [one-to-one relations](https://typeorm.io/docs/relations/one-to-one-relations).

<!-- ZH -->
进一步了解[一对一关系](https://typeorm.io/docs/relations/one-to-one-relations)。

<!-- EN -->
#### `@ManyToOne`

<!-- ZH -->
#### `@ManyToOne`

<!-- EN -->
Many-to-one / one-to-many is a relation where A contains multiple instances of B, but B contains only one instance of A. Let's take for example `User` and `Photo` entities. User can have multiple photos, but each photo is owned by only one single user. Example:

<!-- ZH -->
多对一 / 一对多是一种 A 包含多个 B 实例、但 B 只包含一个 A 实例的关系。以 `User` 和 `Photo` 实体为例。一个用户可以有多张照片，但每张照片只属于一个用户。示例：

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

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

    @Column()
    url: string

    @ManyToOne((type) => User, (user) => user.photos)
    user: User
}
```

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

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

    @Column()
    url: string

    @ManyToOne((type) => User, (user) => user.photos)
    user: User
}
```

<!-- EN -->
Learn more about [many-to-one / one-to-many relations](https://typeorm.io/docs/relations/many-to-one-one-to-many-relations).

<!-- ZH -->
进一步了解[多对一 / 一对多关系](https://typeorm.io/docs/relations/many-to-one-one-to-many-relations)。

<!-- EN -->
#### `@OneToMany`

<!-- ZH -->
#### `@OneToMany`

<!-- EN -->
Many-to-one / one-to-many is a relation where A contains multiple instances of B, but B contains only one instance of A. Let's take for example `User` and `Photo` entities. User can have multiple photos, but each photo is owned by only a single user. Example:

<!-- ZH -->
多对一 / 一对多是一种 A 包含多个 B 实例、但 B 只包含一个 A 实例的关系。以 `User` 和 `Photo` 实体为例。一个用户可以有多张照片，但每张照片只属于一个用户。示例：

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

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

    @Column()
    name: string

    @OneToMany((type) => Photo, (photo) => photo.user)
    photos: Photo[]
}
```

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

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

    @Column()
    name: string

    @OneToMany((type) => Photo, (photo) => photo.user)
    photos: Photo[]
}
```

<!-- EN -->
Learn more about [many-to-one / one-to-many relations](https://typeorm.io/docs/relations/many-to-one-one-to-many-relations).

<!-- ZH -->
进一步了解[多对一 / 一对多关系](https://typeorm.io/docs/relations/many-to-one-one-to-many-relations)。

<!-- EN -->
#### `@ManyToMany`

<!-- ZH -->
#### `@ManyToMany`

<!-- EN -->
Many-to-many is a relation where A contains multiple instances of B, and B contain multiple instances of A. Let's take for example `Question` and `Category` entities. Question can have multiple categories, and each category can have multiple questions. Example:

<!-- ZH -->
多对多是一种 A 包含多个 B 实例、且 B 也包含多个 A 实例的关系。以 `Question` 和 `Category` 实体为例。一个问题可以属于多个分类，而每个分类可以包含多个问题。示例：

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

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

    @Column()
    title: string

    @Column()
    text: string

    @ManyToMany((type) => Category)
    @JoinTable()
    categories: Category[]
}
```

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

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

    @Column()
    title: string

    @Column()
    text: string

    @ManyToMany((type) => Category)
    @JoinTable()
    categories: Category[]
}
```

<!-- EN -->
Learn more about [many-to-many relations](https://typeorm.io/docs/relations/many-to-many-relations).

<!-- ZH -->
进一步了解[多对多关系](https://typeorm.io/docs/relations/many-to-many-relations)。

<!-- EN -->
#### `@JoinColumn`

<!-- ZH -->
#### `@JoinColumn`

<!-- EN -->
Defines which side of the relation contains the join column with a foreign key and allows you to customize the join column name, referenced column name and foreign key name. Example:

<!-- ZH -->
定义关系的哪一侧持有带外键的连接列，并允许你自定义连接列名、被引用列名和外键名。示例：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @ManyToOne((type) => Category)
    @JoinColumn({
        name: "cat_id",
        referencedColumnName: "name",
        foreignKeyConstraintName: "fk_cat_id",
    })
    category: Category
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @ManyToOne((type) => Category)
    @JoinColumn({
        name: "cat_id",
        referencedColumnName: "name",
        foreignKeyConstraintName: "fk_cat_id",
    })
    category: Category
}
```

<!-- EN -->
#### `@JoinTable`

<!-- ZH -->
#### `@JoinTable`

<!-- EN -->
Used for `many-to-many` relations and describes join columns of the "junction" table. Junction table is a special, separate table created automatically by TypeORM with columns referenced to the related entities. You can change the name of the generated "junction" table, the column names inside the junction table, their referenced columns with the `joinColumn`- and `inverseJoinColumn` attributes, and the created foreign keys names. You can also set parameter `synchronize` to false to skip schema update(same way as in @Entity)

<!-- ZH -->
用于 `many-to-many` 关系，描述"中间表"的连接列。中间表是 TypeORM 自动创建的一张特殊独立表，其中的列引用相关联的实体。你可以修改生成的"中间表"的表名、中间表中的列名、它们通过 `joinColumn` 与 `inverseJoinColumn` 属性引用的列，以及所创建的外键名。你也可以把 `synchronize` 参数设为 false 来跳过结构更新（与 @Entity 中一样）

<!-- EN -->
Example:

<!-- ZH -->
示例：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @ManyToMany((type) => Category)
    @JoinTable({
        name: "question_categories",
        joinColumn: {
            name: "question",
            referencedColumnName: "id",
            foreignKeyConstraintName: "fk_question_categories_questionId",
        },
        inverseJoinColumn: {
            name: "category",
            referencedColumnName: "id",
            foreignKeyConstraintName: "fk_question_categories_categoryId",
        },
        synchronize: false,
    })
    categories: Category[]
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @ManyToMany((type) => Category)
    @JoinTable({
        name: "question_categories",
        joinColumn: {
            name: "question",
            referencedColumnName: "id",
            foreignKeyConstraintName: "fk_question_categories_questionId",
        },
        inverseJoinColumn: {
            name: "category",
            referencedColumnName: "id",
            foreignKeyConstraintName: "fk_question_categories_categoryId",
        },
        synchronize: false,
    })
    categories: Category[]
}
```

<!-- EN -->
If the destination table has composite primary keys, then an array of properties must be sent to the `@JoinTable` decorator.

<!-- ZH -->
如果目标表有复合主键，那么必须给 `@JoinTable` 装饰器传入一个属性数组。

<!-- EN -->
#### `@RelationId`

<!-- ZH -->
#### `@RelationId`

<!-- EN -->
Loads id (or ids) of specific relations into properties. For example, if you have a many-to-one `category` in your `Post` entity, you can have a new category id by marking a new property with `@RelationId`. Example:

<!-- ZH -->
把特定关系的 id（或多个 id）加载到属性中。例如，如果你的 `Post` 实体中有一个多对一的 `category`，你可以通过用 `@RelationId` 标记一个新属性来获得一个新的分类 id。示例：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @ManyToOne((type) => Category)
    category: Category

    @RelationId((post: Post) => post.category) // you need to specify target relation
    categoryId: number
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @ManyToOne((type) => Category)
    category: Category

    @RelationId((post: Post) => post.category) // 你需要指定目标关系
    categoryId: number
}
```

<!-- EN -->
This functionality works for all kind of relations, including `many-to-many`:

<!-- ZH -->
该功能适用于所有类型的关系，包括 `many-to-many`：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @ManyToMany((type) => Category)
    categories: Category[]

    @RelationId((post: Post) => post.categories)
    categoryIds: number[]
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @ManyToMany((type) => Category)
    categories: Category[]

    @RelationId((post: Post) => post.categories)
    categoryIds: number[]
}
```

<!-- EN -->
Relation id is used only for representation. The underlying relation is not added/removed/changed when chaining the value.

<!-- ZH -->
关系 id 仅用于展示。修改该值不会添加 / 移除 / 改变底层关系。

<!-- EN -->
## Subscriber and listener decorators

<!-- ZH -->
## 订阅者与监听器装饰器

<!-- EN -->
#### `@AfterLoad`

<!-- ZH -->
#### `@AfterLoad`

<!-- EN -->
You can define a method with any name in entity and mark it with `@AfterLoad` and TypeORM will call it each time the entity is loaded using `QueryBuilder` or repository/manager find methods. Example:

<!-- ZH -->
你可以在实体中定义一个任意名称的方法并用 `@AfterLoad` 标记它，每当该实体通过 `QueryBuilder` 或 repository/manager 的 find 方法被加载时，TypeORM 都会调用它。示例：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @AfterLoad()
    updateCounters() {
        if (this.likesCount === undefined) this.likesCount = 0
    }
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @AfterLoad()
    updateCounters() {
        if (this.likesCount === undefined) this.likesCount = 0
    }
}
```

<!-- EN -->
Learn more about [listeners](https://typeorm.io/docs/listeners-and-subscribers).

<!-- ZH -->
进一步了解[监听器](https://typeorm.io/docs/listeners-and-subscribers)。

<!-- EN -->
#### `@BeforeInsert`

<!-- ZH -->
#### `@BeforeInsert`

<!-- EN -->
You can define a method with any name in entity and mark it with `@BeforeInsert` and TypeORM will call it before the entity is inserted using repository/manager `save`. Example:

<!-- ZH -->
你可以在实体中定义一个任意名称的方法并用 `@BeforeInsert` 标记它，TypeORM 会在该实体通过 repository/manager 的 `save` 被插入之前调用它。示例：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @BeforeInsert()
    updateDates() {
        this.createdDate = new Date()
    }
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @BeforeInsert()
    updateDates() {
        this.createdDate = new Date()
    }
}
```

<!-- EN -->
Learn more about [listeners](https://typeorm.io/docs/listeners-and-subscribers).

<!-- ZH -->
进一步了解[监听器](https://typeorm.io/docs/listeners-and-subscribers)。

<!-- EN -->
#### `@AfterInsert`

<!-- ZH -->
#### `@AfterInsert`

<!-- EN -->
You can define a method with any name in entity and mark it with `@AfterInsert` and TypeORM will call it after the entity is inserted using repository/manager `save`. Example:

<!-- ZH -->
你可以在实体中定义一个任意名称的方法并用 `@AfterInsert` 标记它，TypeORM 会在该实体通过 repository/manager 的 `save` 被插入之后调用它。示例：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @AfterInsert()
    resetCounters() {
        this.counters = 0
    }
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @AfterInsert()
    resetCounters() {
        this.counters = 0
    }
}
```

<!-- EN -->
Learn more about [listeners](https://typeorm.io/docs/listeners-and-subscribers).

<!-- ZH -->
进一步了解[监听器](https://typeorm.io/docs/listeners-and-subscribers)。

<!-- EN -->
#### `@BeforeUpdate`

<!-- ZH -->
#### `@BeforeUpdate`

<!-- EN -->
You can define a method with any name in the entity and mark it with `@BeforeUpdate` and TypeORM will call it before an existing entity is updated using repository/manager `save`. Example:

<!-- ZH -->
你可以在实体中定义一个任意名称的方法并用 `@BeforeUpdate` 标记它，TypeORM 会在已有实体通过 repository/manager 的 `save` 被更新之前调用它。示例：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @BeforeUpdate()
    updateDates() {
        this.updatedDate = new Date()
    }
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @BeforeUpdate()
    updateDates() {
        this.updatedDate = new Date()
    }
}
```

<!-- EN -->
Learn more about [listeners](https://typeorm.io/docs/listeners-and-subscribers).

<!-- ZH -->
进一步了解[监听器](https://typeorm.io/docs/listeners-and-subscribers)。

<!-- EN -->
#### `@AfterUpdate`

<!-- ZH -->
#### `@AfterUpdate`

<!-- EN -->
You can define a method with any name in the entity and mark it with `@AfterUpdate` and TypeORM will call it after an existing entity is updated using repository/manager `save`. Example:

<!-- ZH -->
你可以在实体中定义一个任意名称的方法并用 `@AfterUpdate` 标记它，TypeORM 会在已有实体通过 repository/manager 的 `save` 被更新之后调用它。示例：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @AfterUpdate()
    updateCounters() {
        this.counter = 0
    }
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @AfterUpdate()
    updateCounters() {
        this.counter = 0
    }
}
```

<!-- EN -->
Learn more about [listeners](https://typeorm.io/docs/listeners-and-subscribers).

<!-- ZH -->
进一步了解[监听器](https://typeorm.io/docs/listeners-and-subscribers)。

<!-- EN -->
#### `@BeforeRemove`

<!-- ZH -->
#### `@BeforeRemove`

<!-- EN -->
You can define a method with any name in the entity and mark it with `@BeforeRemove` and TypeORM will call it before an entity is removed using repository/manager `remove`. Example:

<!-- ZH -->
你可以在实体中定义一个任意名称的方法并用 `@BeforeRemove` 标记它，TypeORM 会在该实体通过 repository/manager 的 `remove` 被移除之前调用它。示例：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @BeforeRemove()
    updateStatus() {
        this.status = "removed"
    }
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @BeforeRemove()
    updateStatus() {
        this.status = "removed"
    }
}
```

<!-- EN -->
Learn more about [listeners](https://typeorm.io/docs/listeners-and-subscribers).

<!-- ZH -->
进一步了解[监听器](https://typeorm.io/docs/listeners-and-subscribers)。

<!-- EN -->
#### `@AfterRemove`

<!-- ZH -->
#### `@AfterRemove`

<!-- EN -->
You can define a method with any name in the entity and mark it with `@AfterRemove` and TypeORM will call it after the entity is removed using repository/manager `remove`. Example:

<!-- ZH -->
你可以在实体中定义一个任意名称的方法并用 `@AfterRemove` 标记它，TypeORM 会在该实体通过 repository/manager 的 `remove` 被移除之后调用它。示例：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @AfterRemove()
    updateStatus() {
        this.status = "removed"
    }
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @AfterRemove()
    updateStatus() {
        this.status = "removed"
    }
}
```

<!-- EN -->
Learn more about [listeners](https://typeorm.io/docs/listeners-and-subscribers).

<!-- ZH -->
进一步了解[监听器](https://typeorm.io/docs/listeners-and-subscribers)。

<!-- EN -->
#### `@BeforeSoftRemove`

<!-- ZH -->
#### `@BeforeSoftRemove`

<!-- EN -->
You can define a method with any name in the entity and mark it with `@BeforeSoftRemove` and TypeORM will call it before an entity is soft removed using repository/manager `softRemove`. Example:

<!-- ZH -->
你可以在实体中定义一个任意名称的方法并用 `@BeforeSoftRemove` 标记它，TypeORM 会在该实体通过 repository/manager 的 `softRemove` 被软删除之前调用它。示例：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @BeforeSoftRemove()
    updateStatus() {
        this.status = "soft-removed"
    }
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @BeforeSoftRemove()
    updateStatus() {
        this.status = "soft-removed"
    }
}
```

<!-- EN -->
Learn more about [listeners](https://typeorm.io/docs/listeners-and-subscribers).

<!-- ZH -->
进一步了解[监听器](https://typeorm.io/docs/listeners-and-subscribers)。

<!-- EN -->
#### `@AfterSoftRemove`

<!-- ZH -->
#### `@AfterSoftRemove`

<!-- EN -->
You can define a method with any name in the entity and mark it with `@AfterSoftRemove` and TypeORM will call it after the entity is soft removed using repository/manager `softRemove`. Example:

<!-- ZH -->
你可以在实体中定义一个任意名称的方法并用 `@AfterSoftRemove` 标记它，TypeORM 会在该实体通过 repository/manager 的 `softRemove` 被软删除之后调用它。示例：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @AfterSoftRemove()
    updateStatus() {
        this.status = "soft-removed"
    }
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @AfterSoftRemove()
    updateStatus() {
        this.status = "soft-removed"
    }
}
```

<!-- EN -->
Learn more about [listeners](https://typeorm.io/docs/listeners-and-subscribers).

<!-- ZH -->
进一步了解[监听器](https://typeorm.io/docs/listeners-and-subscribers)。

<!-- EN -->
#### `@BeforeRecover`

<!-- ZH -->
#### `@BeforeRecover`

<!-- EN -->
You can define a method with any name in the entity and mark it with `@BeforeRecover` and TypeORM will call it before an entity is recovered using repository/manager `recover`. Example:

<!-- ZH -->
你可以在实体中定义一个任意名称的方法并用 `@BeforeRecover` 标记它，TypeORM 会在该实体通过 repository/manager 的 `recover` 被恢复之前调用它。示例：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @BeforeRecover()
    updateStatus() {
        this.status = "recovered"
    }
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @BeforeRecover()
    updateStatus() {
        this.status = "recovered"
    }
}
```

<!-- EN -->
Learn more about [listeners](https://typeorm.io/docs/listeners-and-subscribers).

<!-- ZH -->
进一步了解[监听器](https://typeorm.io/docs/listeners-and-subscribers)。

<!-- EN -->
#### `@AfterRecover`

<!-- ZH -->
#### `@AfterRecover`

<!-- EN -->
You can define a method with any name in the entity and mark it with `@AfterRecover` and TypeORM will call it after the entity is recovered using repository/manager `recover`. Example:

<!-- ZH -->
你可以在实体中定义一个任意名称的方法并用 `@AfterRecover` 标记它，TypeORM 会在该实体通过 repository/manager 的 `recover` 被恢复之后调用它。示例：

<!-- EN -->
```typescript
@Entity()
export class Post {
    @AfterRecover()
    updateStatus() {
        this.status = "recovered"
    }
}
```

<!-- ZH -->
```typescript
@Entity()
export class Post {
    @AfterRecover()
    updateStatus() {
        this.status = "recovered"
    }
}
```

<!-- EN -->
Learn more about [listeners](https://typeorm.io/docs/listeners-and-subscribers).

<!-- ZH -->
进一步了解[监听器](https://typeorm.io/docs/listeners-and-subscribers)。

<!-- EN -->
#### `@EventSubscriber`

<!-- ZH -->
#### `@EventSubscriber`

<!-- EN -->
Marks a class as an event subscriber which can listen to specific entity events or any entity's events. Events are fired using `QueryBuilder` and repository/manager methods. Example:

<!-- ZH -->
把一个类标记为事件订阅者，它可以监听特定实体的事件或任意实体的事件。事件通过 `QueryBuilder` 和 repository/manager 方法触发。示例：

<!-- EN -->
```typescript
@EventSubscriber()
export class PostSubscriber implements EntitySubscriberInterface<Post> {
    /**
     * Indicates that this subscriber only listen to Post events.
     */
    listenTo() {
        return Post
    }

    /**
     * Called before post insertion.
     */
    beforeInsert(event: InsertEvent<Post>) {
        console.log(`BEFORE POST INSERTED: `, event.entity)
    }
}
```

<!-- ZH -->
```typescript
@EventSubscriber()
export class PostSubscriber implements EntitySubscriberInterface<Post> {
    /**
     * 表示该订阅者只监听 Post 事件。
     */
    listenTo() {
        return Post
    }

    /**
     * 在 post 插入之前调用。
     */
    beforeInsert(event: InsertEvent<Post>) {
        console.log(`BEFORE POST INSERTED: `, event.entity)
    }
}
```

<!-- EN -->
You can implement any method from `EntitySubscriberInterface`. To listen to any entity, you just omit the `listenTo` method and use `any`:

<!-- ZH -->
你可以实现 `EntitySubscriberInterface` 中的任意方法。要监听任意实体，只需省略 `listenTo` 方法并使用 `any`：

<!-- EN -->
```typescript
@EventSubscriber()
export class PostSubscriber implements EntitySubscriberInterface {
    /**
     * Called before entity insertion.
     */
    beforeInsert(event: InsertEvent<any>) {
        console.log(`BEFORE ENTITY INSERTED: `, event.entity)
    }
}
```

<!-- ZH -->
```typescript
@EventSubscriber()
export class PostSubscriber implements EntitySubscriberInterface {
    /**
     * 在实体插入之前调用。
     */
    beforeInsert(event: InsertEvent<any>) {
        console.log(`BEFORE ENTITY INSERTED: `, event.entity)
    }
}
```

<!-- EN -->
Learn more about [subscribers](https://typeorm.io/docs/listeners-and-subscribers).

<!-- ZH -->
进一步了解[订阅者](https://typeorm.io/docs/listeners-and-subscribers)。

<!-- EN -->
## Other decorators

<!-- ZH -->
## 其他装饰器

<!-- EN -->
#### `@Index`

<!-- ZH -->
#### `@Index`

<!-- EN -->
This decorator allows you to create a database index for a specific column or columns. It also allows you to mark column or columns to be unique. This decorator can be applied to columns or an entity itself. Use it on a column when an index on a single column is needed and use it on the entity when a single index on multiple columns is required. Examples:

<!-- ZH -->
该装饰器让你可以为特定的一个或多个列创建数据库索引。它也让你能把一个或多个列标记为唯一。该装饰器可以应用在列上，也可以应用在实体本身。当需要单列索引时把它用在列上，当需要跨多列的单个索引时把它用在实体上。示例：

<!-- EN -->
```typescript
@Entity()
export class User {
    @Index()
    @Column()
    firstName: string

    @Index({ unique: true })
    @Column()
    lastName: string
}
```

<!-- ZH -->
```typescript
@Entity()
export class User {
    @Index()
    @Column()
    firstName: string

    @Index({ unique: true })
    @Column()
    lastName: string
}
```

<!-- EN -->
```typescript
@Entity()
@Index(["firstName", "lastName"])
@Index(["lastName", "middleName"])
@Index(["firstName", "lastName", "middleName"], { unique: true })
export class User {
    @Column()
    firstName: string

    @Column()
    lastName: string

    @Column()
    middleName: string
}
```

<!-- ZH -->
```typescript
@Entity()
@Index(["firstName", "lastName"])
@Index(["lastName", "middleName"])
@Index(["firstName", "lastName", "middleName"], { unique: true })
export class User {
    @Column()
    firstName: string

    @Column()
    lastName: string

    @Column()
    middleName: string
}
```

<!-- EN -->
Learn more about [indexes](https://typeorm.io/docs/indexes).

<!-- ZH -->
进一步了解[索引](https://typeorm.io/docs/indexes)。

<!-- EN -->
#### `@Unique`

<!-- ZH -->
#### `@Unique`

<!-- EN -->
This decorator allows you to create a database unique constraint for a specific column or columns. This decorator can be applied only to an entity itself. You must specify the entity field names (not database column names) as arguments.

<!-- ZH -->
该装饰器让你可以为特定的一个或多个列创建数据库唯一约束。该装饰器只能应用在实体本身。你必须把实体字段名（而不是数据库列名）作为参数传入。

<!-- EN -->
Examples:

<!-- ZH -->
示例：

<!-- EN -->
```typescript
@Entity()
@Unique(["firstName"])
@Unique(["lastName", "middleName"])
@Unique("UQ_NAMES", ["firstName", "lastName", "middleName"])
export class User {
    @Column({ name: "first_name" })
    firstName: string

    @Column({ name: "last_name" })
    lastName: string

    @Column({ name: "middle_name" })
    middleName: string
}
```

<!-- ZH -->
```typescript
@Entity()
@Unique(["firstName"])
@Unique(["lastName", "middleName"])
@Unique("UQ_NAMES", ["firstName", "lastName", "middleName"])
export class User {
    @Column({ name: "first_name" })
    firstName: string

    @Column({ name: "last_name" })
    lastName: string

    @Column({ name: "middle_name" })
    middleName: string
}
```

<!-- EN -->
> Note: MySQL stores unique constraints as unique indexes

<!-- ZH -->
> 注意：MySQL 把唯一约束存储为唯一索引

<!-- EN -->
#### `@Check`

<!-- ZH -->
#### `@Check`

<!-- EN -->
This decorator allows you to create a database check constraint for a specific column or columns. This decorator can be applied only to an entity itself.

<!-- ZH -->
该装饰器让你可以为特定的一个或多个列创建数据库检查约束。该装饰器只能应用在实体本身。

<!-- EN -->
Examples:

<!-- ZH -->
示例：

<!-- EN -->
```typescript
@Entity()
@Check(`"firstName" <> 'John' AND "lastName" <> 'Doe'`)
@Check(`"age" > 18`)
export class User {
    @Column()
    firstName: string

    @Column()
    lastName: string

    @Column()
    age: number
}
```

<!-- ZH -->
```typescript
@Entity()
@Check(`"firstName" <> 'John' AND "lastName" <> 'Doe'`)
@Check(`"age" > 18`)
export class User {
    @Column()
    firstName: string

    @Column()
    lastName: string

    @Column()
    age: number
}
```

<!-- EN -->
> Note: MySQL does not support check constraints.

<!-- ZH -->
> 注意：MySQL 不支持检查约束。

<!-- EN -->
#### `@Exclusion`

<!-- ZH -->
#### `@Exclusion`

<!-- EN -->
This decorator allows you to create a database exclusion constraint for a specific column or columns. This decorator can be applied only to an entity itself.

<!-- ZH -->
该装饰器让你可以为特定的一个或多个列创建数据库排他约束。该装饰器只能应用在实体本身。

<!-- EN -->
Examples:

<!-- ZH -->
示例：

<!-- EN -->
```typescript
@Entity()
@Exclusion(`USING gist ("room" WITH =, tsrange("from", "to") WITH &&)`)
export class RoomBooking {
    @Column()
    room: string

    @Column()
    from: Date

    @Column()
    to: Date
}
```

<!-- ZH -->
```typescript
@Entity()
@Exclusion(`USING gist ("room" WITH =, tsrange("from", "to") WITH &&)`)
export class RoomBooking {
    @Column()
    room: string

    @Column()
    from: Date

    @Column()
    to: Date
}
```

<!-- EN -->
> Note: Only PostgreSQL supports exclusion constraints.

<!-- ZH -->
> 注意：只有 PostgreSQL 支持排他约束。

<!-- EN -->
#### `@ForeignKey`

<!-- ZH -->
#### `@ForeignKey`

<!-- EN -->
This decorator allows you to create a database foreign key for a specific column or columns. This decorator can be applied to columns or an entity itself. Use it on a column when an foreign key on a single column is needed and use it on the entity when a single foreign key on multiple columns is required.

<!-- ZH -->
该装饰器让你可以为特定的一个或多个列创建数据库外键。该装饰器可以应用在列上，也可以应用在实体本身。当需要单列外键时把它用在列上，当需要跨多列的单个外键时把它用在实体上。

<!-- EN -->
> Note: **Do not use this decorator with relations.** Foreign keys are created automatically for relations which you define using [Relation decorators](#relation-decorators) (`@ManyToOne`, `@OneToOne`, etc). The `@ForeignKey` decorator should only be used to create foreign keys in the database when you don't want to define an equivalent entity relationship.

<!-- ZH -->
> 注意：**不要把该装饰器与关系一起使用。** 用[关系装饰器](#relation-decorators)（`@ManyToOne`、`@OneToOne` 等）定义的关系会自动创建外键。只有当你不想定义等价的实体关系、却仍想在数据库中创建外键时，才应使用 `@ForeignKey` 装饰器。

<!-- EN -->
Examples:

<!-- ZH -->
示例：

<!-- EN -->
```typescript
@Entity("orders")
@ForeignKey(() => City, ["cityId", "countryCode"], ["id", "countryCode"])
export class Order {
    @PrimaryColumn()
    id: number

    @Column("uuid", { name: "user_uuid" })
    @ForeignKey<User>("User", "uuid", { name: "FK_user_uuid" })
    userUuid: string

    @Column({ length: 2 })
    @ForeignKey(() => Country, "code")
    countryCode: string

    @Column()
    @ForeignKey("cities")
    cityId: number

    @Column()
    dispatchCountryCode: string

    @ManyToOne(() => Country)
    dispatchCountry: Country

    @Column()
    dispatchCityId: number

    @ManyToOne(() => City)
    dispatchCity: City
}
```

<!-- ZH -->
```typescript
@Entity("orders")
@ForeignKey(() => City, ["cityId", "countryCode"], ["id", "countryCode"])
export class Order {
    @PrimaryColumn()
    id: number

    @Column("uuid", { name: "user_uuid" })
    @ForeignKey<User>("User", "uuid", { name: "FK_user_uuid" })
    userUuid: string

    @Column({ length: 2 })
    @ForeignKey(() => Country, "code")
    countryCode: string

    @Column()
    @ForeignKey("cities")
    cityId: number

    @Column()
    dispatchCountryCode: string

    @ManyToOne(() => Country)
    dispatchCountry: Country

    @Column()
    dispatchCityId: number

    @ManyToOne(() => City)
    dispatchCity: City
}
```

<!-- EN -->
```typescript
@Entity("cities")
@Unique(["id", "countryCode"])
export class City {
    @PrimaryColumn()
    id: number

    @Column({ length: 2 })
    @ForeignKey("countries", { onDelete: "CASCADE", onUpdate: "CASCADE" })
    countryCode: string

    @Column()
    name: string
}
```

<!-- ZH -->
```typescript
@Entity("cities")
@Unique(["id", "countryCode"])
export class City {
    @PrimaryColumn()
    id: number

    @Column({ length: 2 })
    @ForeignKey("countries", { onDelete: "CASCADE", onUpdate: "CASCADE" })
    countryCode: string

    @Column()
    name: string
}
```

<!-- EN -->
```typescript
@Entity("countries")
export class Country {
    @PrimaryColumn({ length: 2 })
    code: string

    @Column()
    name: string
}
```

<!-- ZH -->
```typescript
@Entity("countries")
export class Country {
    @PrimaryColumn({ length: 2 })
    code: string

    @Column()
    name: string
}
```

<!-- EN -->
```typescript
@Entity("users")
export class User {
    @PrimaryColumn({ name: "ref" })
    id: number

    @Column("uuid", { unique: true })
    uuid: string
}
```

<!-- ZH -->
```typescript
@Entity("users")
export class User {
    @PrimaryColumn({ name: "ref" })
    id: number

    @Column("uuid", { unique: true })
    uuid: string
}
```
