# 实体

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

---

<!-- EN -->
# Entities

<!-- ZH -->
# 实体

<!-- EN -->
## What is an Entity?

<!-- ZH -->
## 什么是实体？

<!-- EN -->
Entity is a class that maps to a database table (or collection when using MongoDB). You can create an entity by defining a new class and mark it with `@Entity()`:

<!-- ZH -->
实体是一个映射到数据库表的类（使用 MongoDB 时则映射到集合）。你可以通过定义一个新类并用 `@Entity()` 标记它来创建实体：

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

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

    @Column()
    firstName: string

    @Column()
    lastName: string

    @Column()
    isActive: boolean
}
```

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

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

    @Column()
    firstName: string

    @Column()
    lastName: string

    @Column()
    isActive: boolean
}
```

<!-- EN -->
This will create following database table:

<!-- ZH -->
这会创建如下数据库表：

<!-- EN -->
```text
+-------------+--------------+----------------------------+
|                          user                           |
+-------------+--------------+----------------------------+
| id          | int          | PRIMARY KEY AUTO_INCREMENT |
| firstName   | varchar(255) |                            |
| lastName    | varchar(255) |                            |
| isActive    | boolean      |                            |
+-------------+--------------+----------------------------+
```

<!-- ZH -->
```text
+-------------+--------------+----------------------------+
|                          user                           |
+-------------+--------------+----------------------------+
| id          | int          | PRIMARY KEY AUTO_INCREMENT |
| firstName   | varchar(255) |                            |
| lastName    | varchar(255) |                            |
| isActive    | boolean      |                            |
+-------------+--------------+----------------------------+
```

<!-- EN -->
Basic entities consist of columns and relations. Each entity **MUST** have a primary column (or an `ObjectId` column if are using MongoDB).

<!-- ZH -->
基本的实体由列和关系组成。每个实体 **必须** 有一个主键列（如果使用 MongoDB，则是一个 `ObjectId` 列）。

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

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

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

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

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

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

<!-- EN -->
Or you can specify the whole directory with all entities inside - and all of them will be loaded:

<!-- ZH -->
或者你可以直接指定包含所有实体的整个目录——它们都会被加载进来：

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

const dataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "test",
    password: "test",
    database: "test",
    entities: [__dirname + "/entities/**/*{.js,.ts}"],
})
```

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

const dataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "test",
    password: "test",
    database: "test",
    entities: [__dirname + "/entities/**/*{.js,.ts}"],
})
```

<!-- EN -->
If you want to use an alternative table name for the `User` entity you can specify it in `@Entity`: `@Entity("my_users")`. If you want to set a base prefix for all database tables in your application you can specify `entityPrefix` in data source options.

<!-- ZH -->
如果你想为 `User` 实体使用另一个表名，可以在 `@Entity` 中指定：`@Entity("my_users")`。如果你想为应用中所有数据库表设置一个基础前缀，可以在数据源选项中指定 `entityPrefix`。

<!-- EN -->
When using an entity constructor its arguments **must be optional**. Since ORM creates instances of entity classes when loading from the database, therefore it is not aware of your constructor arguments.

<!-- ZH -->
使用实体构造函数时，其参数**必须是可选的**。因为 ORM 在从数据库加载时会创建实体类的实例，它并不知道你的构造函数参数。

<!-- EN -->
Learn more about parameters `@Entity` in [Decorators reference](https://typeorm.io/docs/help/decorator-reference).

<!-- ZH -->
在[装饰器参考](https://typeorm.io/docs/help/decorator-reference)中进一步了解 `@Entity` 的参数。

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

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

<!-- EN -->
Since database tables consist of columns your entities must consist of columns too. Each entity class property you marked with `@Column` will be mapped to a database table column.

<!-- ZH -->
既然数据库表由列组成，你的实体也必须由列组成。你用 `@Column` 标记的每个实体类属性都会映射到数据库表的一列。

<!-- EN -->
### Primary columns

<!-- ZH -->
### 主键列

<!-- EN -->
Each entity must have at least one primary column. There are several types of primary columns:

<!-- ZH -->
每个实体必须至少有一个主键列。主键列有几种类型：

<!-- EN -->
* `@PrimaryColumn()` creates a primary column which takes any value of any type. You can specify the column type. If you don't specify a column type it will be inferred from the property type. The example below will create id with `int` as type which you must manually assign before save.

<!-- ZH -->
* `@PrimaryColumn()` 创建一个可接受任意类型任意值的主键列。你可以指定列类型。如果不指定列类型，它会从属性类型推断出来。下面的示例会创建类型为 `int` 的 id，你必须在保存前手动赋值。

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

@Entity()
export class User {
    @PrimaryColumn()
    id: number
}
```

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

@Entity()
export class User {
    @PrimaryColumn()
    id: number
}
```

<!-- EN -->
* `@PrimaryGeneratedColumn()` creates a primary column which value will be automatically generated with an auto-increment value. It will create `int` column with `auto-increment`/`serial`/`sequence`/`identity` (depend on the database and configuration provided). You don't have to manually assign its value before save - value will be automatically generated.

<!-- ZH -->
* `@PrimaryGeneratedColumn()` 创建一个主键列，其值会以自增方式自动生成。它会创建带 `auto-increment`/`serial`/`sequence`/`identity` 的 `int` 列（取决于数据库和所提供的配置）。你不必在保存前手动赋值——值会自动生成。

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

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

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

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

<!-- EN -->
* `@PrimaryGeneratedColumn("uuid")` creates a primary column which value will be automatically generated with `uuid`. Uuid is a unique string id. You don't have to manually assign its value before save - value will be automatically generated.

<!-- ZH -->
* `@PrimaryGeneratedColumn("uuid")` 创建一个主键列，其值会以 `uuid` 自动生成。Uuid 是一个唯一的字符串 id。你不必在保存前手动赋值——值会自动生成。

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

@Entity()
export class User {
    @PrimaryGeneratedColumn("uuid")
    id: string
}
```

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

@Entity()
export class User {
    @PrimaryGeneratedColumn("uuid")
    id: string
}
```

<!-- EN -->
You can have composite primary columns as well:

<!-- ZH -->
你也可以使用复合主键列：

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

@Entity()
export class User {
    @PrimaryColumn()
    firstName: string

    @PrimaryColumn()
    lastName: string
}
```

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

@Entity()
export class User {
    @PrimaryColumn()
    firstName: string

    @PrimaryColumn()
    lastName: string
}
```

<!-- EN -->
When you save entities using `save` it always tries to find an entity in the database with the given entity id (or ids). If id/ids are found then it will update this row in the database. If there is no row with the id/ids, a new row will be inserted.

<!-- ZH -->
当你用 `save` 保存实体时，它总会尝试在数据库中查找具有给定实体 id（或多个 id）的实体。如果找到了 id/ids，就会更新数据库中的这一行。如果没有对应 id/ids 的行，则会插入新行。

<!-- EN -->
To find an entity by id you can use `manager.findOneBy` or `repository.findOneBy`. Example:

<!-- ZH -->
要按 id 查找实体，可以使用 `manager.findOneBy` 或 `repository.findOneBy`。示例：

<!-- EN -->
```typescript
// find one by id with single primary key
const person = await dataSource.manager.findOneBy(Person, { id: 1 })
const person = await dataSource.getRepository(Person).findOneBy({ id: 1 })

// find one by id with composite primary keys
const user = await dataSource.manager.findOneBy(User, {
    firstName: "Timber",
    lastName: "Saw",
})
const user = await dataSource.getRepository(User).findOneBy({
    firstName: "Timber",
    lastName: "Saw",
})
```

<!-- ZH -->
```typescript
// 单主键时按 id 查找一条
const person = await dataSource.manager.findOneBy(Person, { id: 1 })
const person = await dataSource.getRepository(Person).findOneBy({ id: 1 })

// 复合主键时按 id 查找一条
const user = await dataSource.manager.findOneBy(User, {
    firstName: "Timber",
    lastName: "Saw",
})
const user = await dataSource.getRepository(User).findOneBy({
    firstName: "Timber",
    lastName: "Saw",
})
```

<!-- EN -->
### Special columns

<!-- ZH -->
### 特殊列

<!-- EN -->
There are several special column types with additional functionality available:

<!-- ZH -->
有几种带额外功能的特殊列类型可用：

<!-- EN -->
* `@CreateDateColumn` is a special column that is automatically set to the entity's insertion date. You don't need to set this column - it will be automatically set.

<!-- ZH -->
* `@CreateDateColumn` 是一个特殊列，会被自动设置为实体的插入时间。你不需要设置这一列——它会被自动设置。

<!-- EN -->
* `@UpdateDateColumn` is a special column that is automatically set to the entity's update time each time you call `save` of entity manager or repository, or during `upsert` operations when an update occurs. You don't need to set this column - it will be automatically set.

<!-- ZH -->
* `@UpdateDateColumn` 是一个特殊列，每次你调用 entity manager 或 repository 的 `save`，或在 `upsert` 操作中发生更新时，它都会被自动设置为实体的更新时间。你不需要设置这一列——它会被自动设置。

<!-- EN -->
* `@DeleteDateColumn` is a 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. If the @DeleteDateColumn is set, the default scope will be "non-deleted".

<!-- ZH -->
* `@DeleteDateColumn` 是一个特殊列，每次你调用 entity manager 或 repository 的软删除时，它都会被自动设置为实体的删除时间。你不需要设置这一列——它会被自动设置。如果设置了 @DeleteDateColumn，默认作用域将是"未删除"。

<!-- EN -->
* `@VersionColumn` is a special column that is automatically set to the version of the entity (incremental number) each time you call `save` of entity manager or repository, or during `upsert` operations when an update occurs. You don't need to set this column - it will be automatically set.

<!-- ZH -->
* `@VersionColumn` 是一个特殊列，每次你调用 entity manager 或 repository 的 `save`，或在 `upsert` 操作中发生更新时，它都会被自动设置为实体的版本号（递增数字）。你不需要设置这一列——它会被自动设置。

<!-- EN -->
## Column types

<!-- ZH -->
## 列类型

<!-- EN -->
TypeORM supports all of the most commonly used database-supported column types. Column types are database-type specific - this provides more flexibility on how your database schema will look like.

<!-- ZH -->
TypeORM 支持所有最常用的、数据库所支持的列类型。列类型是数据库专属的——这让你能更灵活地控制数据库结构的呈现方式。

<!-- EN -->
You can specify column type as first parameter of `@Column` or in the column options of `@Column`, for example:

<!-- ZH -->
你可以把列类型作为 `@Column` 的第一个参数指定，也可以放在 `@Column` 的列选项中，例如：

<!-- EN -->
```typescript
@Column("int")
```

<!-- ZH -->
```typescript
@Column("int")
```

<!-- EN -->
or

<!-- ZH -->
或者

<!-- EN -->
```typescript
@Column({ type: "int" })
```

<!-- ZH -->
```typescript
@Column({ type: "int" })
```

<!-- EN -->
If you want to specify additional type parameters you can do it via column options. For example:

<!-- ZH -->
如果你想指定额外的类型参数，可以通过列选项来做。例如：

<!-- EN -->
```typescript
@Column("varchar", { length: 200 })
```

<!-- ZH -->
```typescript
@Column("varchar", { length: 200 })
```

<!-- EN -->
> Note about `bigint` type: `bigint` column type, used in SQL databases, doesn't fit into the regular `number` type and maps property to a `string` instead.

<!-- ZH -->
> 关于 `bigint` 类型的说明：SQL 数据库中使用的 `bigint` 列类型无法放进常规的 `number` 类型，因此会把属性映射为 `string`。

<!-- EN -->
### `enum` column type

<!-- ZH -->
### `enum` 列类型

<!-- EN -->
`enum` column type is supported by `postgres` and `mysql`. There are various possible column definitions:

<!-- ZH -->
`enum` 列类型受 `postgres` 和 `mysql` 支持。有多种可能的列定义方式：

<!-- EN -->
Using typescript enums:

<!-- ZH -->
使用 TypeScript 枚举：

<!-- EN -->
```typescript
export enum UserRole {
    ADMIN = "admin",
    EDITOR = "editor",
    GHOST = "ghost",
}

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

    @Column({
        type: "enum",
        enum: UserRole,
        default: UserRole.GHOST,
    })
    role: UserRole
}
```

<!-- ZH -->
```typescript
export enum UserRole {
    ADMIN = "admin",
    EDITOR = "editor",
    GHOST = "ghost",
}

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

    @Column({
        type: "enum",
        enum: UserRole,
        default: UserRole.GHOST,
    })
    role: UserRole
}
```

<!-- EN -->
> Note: String, numeric and heterogeneous enums are supported.

<!-- ZH -->
> 注意：支持字符串枚举、数字枚举和异构枚举。

<!-- EN -->
Using array with enum values:

<!-- ZH -->
使用包含枚举值的数组：

<!-- EN -->
```typescript
export type UserRoleType = "admin" | "editor" | "ghost",

@Entity()
export class User {

    @PrimaryGeneratedColumn()
    id: number;

    @Column({
        type: "enum",
        enum: ["admin", "editor", "ghost"],
        default: "ghost"
    })
    role: UserRoleType
}
```

<!-- ZH -->
```typescript
export type UserRoleType = "admin" | "editor" | "ghost",

@Entity()
export class User {

    @PrimaryGeneratedColumn()
    id: number;

    @Column({
        type: "enum",
        enum: ["admin", "editor", "ghost"],
        default: "ghost"
    })
    role: UserRoleType
}
```

<!-- EN -->
### `simple-array` column type

<!-- ZH -->
### `simple-array` 列类型

<!-- EN -->
There is a special column type called `simple-array` which can store primitive array values in a single string column. All values are separated by a comma. For example:

<!-- ZH -->
有一种特殊列类型叫 `simple-array`，它可以把原始数组值存进单个字符串列中。所有值用逗号分隔。例如：

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

    @Column("simple-array")
    names: string[]
}
```

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

    @Column("simple-array")
    names: string[]
}
```

<!-- EN -->
```typescript
const user = new User()
user.names = ["Alexander", "Alex", "Sasha", "Shurik"]
```

<!-- ZH -->
```typescript
const user = new User()
user.names = ["Alexander", "Alex", "Sasha", "Shurik"]
```

<!-- EN -->
Will be stored in a single database column as `Alexander,Alex,Sasha,Shurik` value. When you'll load data from the database, the names will be returned as an array of names, just like you stored them.

<!-- ZH -->
它会以 `Alexander,Alex,Sasha,Shurik` 这个值存进单个数据库列中。当你从数据库加载数据时，names 会被还原成一个名字数组，就像你当初存进去的那样。

<!-- EN -->
Note you **MUST NOT** have any comma in values you write.

<!-- ZH -->
注意，你写入的值中 **绝不能** 包含逗号。

<!-- EN -->
### `simple-json` column type

<!-- ZH -->
### `simple-json` 列类型

<!-- EN -->
There is a special column type called `simple-json` which can store any values which can be stored in database via JSON.stringify. Very useful when you do not have json type in your database and you want to store and load object without any hassle. For example:

<!-- ZH -->
有一种特殊列类型叫 `simple-json`，它可以存储任何能通过 JSON.stringify 存进数据库的值。当你的数据库没有 json 类型、但又想毫无麻烦地存取对象时，它非常有用。例如：

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

    @Column("simple-json")
    profile: { name: string; nickname: string }
}
```

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

    @Column("simple-json")
    profile: { name: string; nickname: string }
}
```

<!-- EN -->
```typescript
const user = new User()
user.profile = { name: "John", nickname: "Malkovich" }
```

<!-- ZH -->
```typescript
const user = new User()
user.profile = { name: "John", nickname: "Malkovich" }
```

<!-- EN -->
Will be stored in a single database column as `{"name":"John","nickname":"Malkovich"}` value. When you'll load data from the database, you will have your object/array/primitive back via JSON.parse

<!-- ZH -->
它会以 `{"name":"John","nickname":"Malkovich"}` 这个值存进单个数据库列中。当你从数据库加载数据时，会通过 JSON.parse 拿回你的对象 / 数组 / 原始值

<!-- EN -->
### `simple-enum` column type

<!-- ZH -->
### `simple-enum` 列类型

<!-- EN -->
There is a special column type called `simple-enum` which stores enum values in a single column. It is useful when the same entity has to work across databases that do not all support native enums, because TypeORM maps it to whatever each driver supports: a native enum type where one exists, and a string column with a `CHECK` constraint elsewhere. For example:

<!-- ZH -->
有一种特殊列类型叫 `simple-enum`，它把枚举值存在单个列中。当同一个实体需要跨多个并非都支持原生枚举的数据库工作时，它很有用，因为 TypeORM 会把它映射成各驱动所支持的形式：有原生枚举类型就用原生枚举类型，否则就用带 `CHECK` 约束的字符串列。例如：

<!-- EN -->
```typescript
export enum UserRole {
    ADMIN = "admin",
    EDITOR = "editor",
    GHOST = "ghost",
}

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

    @Column({
        type: "simple-enum",
        enum: UserRole,
        default: UserRole.GHOST,
    })
    role: UserRole
}
```

<!-- ZH -->
```typescript
export enum UserRole {
    ADMIN = "admin",
    EDITOR = "editor",
    GHOST = "ghost",
}

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

    @Column({
        type: "simple-enum",
        enum: UserRole,
        default: UserRole.GHOST,
    })
    role: UserRole
}
```

<!-- EN -->
The allowed values can also be given as an array:

<!-- ZH -->
允许的值也可以用数组给出：

<!-- EN -->
```typescript
export type UserRoleType = "admin" | "editor" | "ghost"

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

    @Column({
        type: "simple-enum",
        enum: ["admin", "editor", "ghost"],
        default: "ghost",
    })
    role: UserRoleType
}
```

<!-- ZH -->
```typescript
export type UserRoleType = "admin" | "editor" | "ghost"

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

    @Column({
        type: "simple-enum",
        enum: ["admin", "editor", "ghost"],
        default: "ghost",
    })
    role: UserRoleType
}
```

<!-- EN -->
> Note: String, numeric and heterogeneous enums are supported. Numeric values are converted back to numbers when loading.

<!-- ZH -->
> 注意：支持字符串枚举、数字枚举和异构枚举。加载时数字值会被转换回数字。

<!-- EN -->
How the values are stored depends on the driver:

<!-- ZH -->
值的存储方式取决于驱动：

<!-- EN -->
* MySQL, MariaDB and Aurora MySQL use the native `enum` column type
* PostgreSQL, CockroachDB and Aurora PostgreSQL use a native `enum` database type
* SQLite (including `better-sqlite3`, `sql.js`, Cordova, Expo, NativeScript, Capacitor and React Native) and SQL Server store the values in a string column and add a `CHECK` constraint
* SAP HANA stores the values in an `nvarchar` column without a `CHECK` constraint

<!-- ZH -->
* MySQL、MariaDB 和 Aurora MySQL 使用原生 `enum` 列类型
* PostgreSQL、CockroachDB 和 Aurora PostgreSQL 使用原生 `enum` 数据库类型
* SQLite（包括 `better-sqlite3`、`sql.js`、Cordova、Expo、NativeScript、Capacitor 和 React Native）以及 SQL Server 把值存在字符串列中并加上 `CHECK` 约束
* SAP HANA 把值存在 `nvarchar` 列中，不加 `CHECK` 约束

<!-- EN -->
`simple-enum` is not supported by Oracle or Spanner.

<!-- ZH -->
Oracle 和 Spanner 不支持 `simple-enum`。

<!-- EN -->
On PostgreSQL, CockroachDB and SQLite you can store an array of enum values with `array: true`:

<!-- ZH -->
在 PostgreSQL、CockroachDB 和 SQLite 上，你可以用 `array: true` 存储枚举值数组：

<!-- EN -->
```typescript
@Column({
    type: "simple-enum",
    enum: UserRole,
    array: true,
    default: [UserRole.EDITOR],
})
roles: UserRole[]
```

<!-- ZH -->
```typescript
@Column({
    type: "simple-enum",
    enum: UserRole,
    array: true,
    default: [UserRole.EDITOR],
})
roles: UserRole[]
```

<!-- EN -->
Arrays are stored as a comma-separated list on SQLite, so enum values must not contain a comma. No `CHECK` constraint is created for array columns on SQLite.

<!-- ZH -->
在 SQLite 上数组会以逗号分隔列表的形式存储，因此枚举值不能包含逗号。在 SQLite 上不会为数组列创建 `CHECK` 约束。

<!-- EN -->
### Columns with generated values

<!-- ZH -->
### 带生成值的列

<!-- EN -->
You can create column with generated value using `@Generated` decorator. For example:

<!-- ZH -->
你可以用 `@Generated` 装饰器创建带生成值的列。例如：

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

    @Column()
    @Generated("uuid")
    uuid: string
}
```

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

    @Column()
    @Generated("uuid")
    uuid: string
}
```

<!-- EN -->
`uuid` value will be automatically generated and stored into the database.

<!-- ZH -->
`uuid` 值会被自动生成并存入数据库。

<!-- EN -->
Besides "uuid" there is also "increment", "identity" (Postgres 10+ only) and "rowid" (CockroachDB only) generated types, however there are some limitations on some database platforms with this type of generation (for example some databases can only have one increment column, or some of them require increment to be a primary key).

<!-- ZH -->
除了 "uuid" 之外，还有 "increment"、"identity"（仅 Postgres 10+）和 "rowid"（仅 CockroachDB）这几种生成类型，不过这种生成方式在某些数据库平台上存在一些限制（例如有些数据库只能有一个 increment 列，或者有些要求 increment 列必须是主键）。

<!-- EN -->
### Vector columns

<!-- ZH -->
### 向量列

<!-- EN -->
Vector columns are supported on MariaDB/MySQL, Microsoft SQL Server, PostgreSQL (via [`pgvector`](https://github.com/pgvector/pgvector) extension) and SAP HANA Cloud, enabling storing and querying vector embeddings for similarity search and machine learning applications.

<!-- ZH -->
向量列在 MariaDB/MySQL、Microsoft SQL Server、PostgreSQL（通过 [`pgvector`](https://github.com/pgvector/pgvector) 扩展）和 SAP HANA Cloud 上受支持，可用于存储和查询向量嵌入，服务于相似性搜索与机器学习应用。

<!-- EN -->
TypeORM supports both `vector` and `halfvec` column types across databases:

<!-- ZH -->
TypeORM 在各数据库上同时支持 `vector` 和 `halfvec` 两种列类型：

<!-- EN -->
* `vector` - stores vectors as 4-byte floats (single precision)

<!-- ZH -->
* `vector` - 以 4 字节浮点数（单精度）存储向量

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

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

<!-- EN -->
  * MariaDB/MySQL: native `vector` type
  * Microsoft SQL Server: native `vector` type
  * PostgreSQL: `vector` type, available via `pgvector` extension
  * SAP HANA Cloud: alias for `real_vector` type

<!-- ZH -->
  * MariaDB/MySQL：原生 `vector` 类型
  * Microsoft SQL Server：原生 `vector` 类型
  * PostgreSQL：`vector` 类型，通过 `pgvector` 扩展提供
  * SAP HANA Cloud：`real_vector` 类型的别名

<!-- EN -->
* `halfvec` - stores vectors as 2-byte floats (half precision) for memory efficiency

<!-- ZH -->
* `halfvec` - 以 2 字节浮点数（半精度）存储向量，更节省内存

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

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

<!-- EN -->
  * PostgreSQL: `halfvec` type, available via `pgvector` extension
  * SAP HANA Cloud: alias for `half_vector` type

<!-- ZH -->
  * PostgreSQL：`halfvec` 类型，通过 `pgvector` 扩展提供
  * SAP HANA Cloud：`half_vector` 类型的别名

<!-- EN -->
You can specify the number of vector dimensions using the `length` option:

<!-- ZH -->
你可以用 `length` 选项指定向量维度数：

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

    // Vector without specified dimensions
    @Column("vector")
    embedding: number[] | Buffer

    // Vector with 3 dimensions: vector(3)
    @Column("vector", { length: 3 })
    embedding_3d: number[] | Buffer

    // Half-precision vector with 4 dimensions: halfvec(4) (works on PostgreSQL and SAP HANA only)
    @Column("halfvec", { length: 4 })
    halfvec_embedding: number[] | Buffer
}
```

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

    // 未指定维度的向量
    @Column("vector")
    embedding: number[] | Buffer

    // 3 维向量：vector(3)
    @Column("vector", { length: 3 })
    embedding_3d: number[] | Buffer

    // 4 维半精度向量：halfvec(4)（仅在 PostgreSQL 和 SAP HANA 上可用）
    @Column("halfvec", { length: 4 })
    halfvec_embedding: number[] | Buffer
}
```

<!-- EN -->
> **Note**:
>
> * **MariaDB/MySQL**: Vectors are supported since MariaDB 11.7 and MySQL 9
> * **Microsoft SQL Server**: Vector type support requires SQL Server 2025 (17.x) or newer.
> * **PostgreSQL**: Vector columns require the `pgvector` extension to be installed. The extension provides the vector data types and similarity operators.
> * **SAP HANA**: Vector columns require SAP HANA Cloud (2024Q1+) and a supported version of `@sap/hana-client`.

<!-- ZH -->
> **注意**：
>
> * **MariaDB/MySQL**：自 MariaDB 11.7 和 MySQL 9 起支持向量
> * **Microsoft SQL Server**：向量类型支持需要 SQL Server 2025（17.x）或更高版本。
> * **PostgreSQL**：向量列需要安装 `pgvector` 扩展。该扩展提供向量数据类型和相似性操作符。
> * **SAP HANA**：向量列需要 SAP HANA Cloud（2024Q1+）以及受支持版本的 `@sap/hana-client`。

<!-- EN -->
### Spatial columns

<!-- ZH -->
### 空间列

<!-- EN -->
Microsoft SQLServer, MySQL/MariaDB, PostgreSQL/CockroachDB and SAP HANA all support spatial columns. TypeORM's support for each varies slightly between databases, particularly as the column names vary between databases.

<!-- ZH -->
Microsoft SQLServer、MySQL/MariaDB、PostgreSQL/CockroachDB 和 SAP HANA 都支持空间列。TypeORM 对各数据库的支持略有差异，尤其是列名在不同数据库之间并不相同。

<!-- EN -->
MS SQL, MySQL/MariaDB and SAP HANA use geometries in the [well-known text (WKT)](https://en.wikipedia.org/wiki/Well-known_text) format, so geometry columns should be tagged with the `string` type.

<!-- ZH -->
MS SQL、MySQL/MariaDB 和 SAP HANA 使用 [well-known text (WKT)](https://en.wikipedia.org/wiki/Well-known_text) 格式的几何体，因此几何列应标记为 `string` 类型。

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

@Entity()
export class Thing {
    @PrimaryColumn()
    id: number

    @Column("point")
    point: string

    @Column("linestring")
    linestring: string
}

...

const thing = new Thing()
thing.point = "POINT(1 1)"
thing.linestring = "LINESTRING(0 0,1 1,2 2)"
```

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

@Entity()
export class Thing {
    @PrimaryColumn()
    id: number

    @Column("point")
    point: string

    @Column("linestring")
    linestring: string
}

...

const thing = new Thing()
thing.point = "POINT(1 1)"
thing.linestring = "LINESTRING(0 0,1 1,2 2)"
```

<!-- EN -->
For Postgres/CockroachDB, see [Postgis Data Types](https://typeorm.io/docs/drivers/postgres#spatial-columns)

<!-- ZH -->
对于 Postgres/CockroachDB，请参阅 [Postgis 数据类型](https://typeorm.io/docs/drivers/postgres#spatial-columns)

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

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

<!-- EN -->
Column options defines additional options for your entity columns. You can specify column options on `@Column`:

<!-- ZH -->
列选项为你的实体列定义额外选项。你可以在 `@Column` 上指定列选项：

<!-- EN -->
```typescript
@Column({
    type: "varchar",
    length: 150,
    unique: true,
    // ...
})
name: string;
```

<!-- ZH -->
```typescript
@Column({
    type: "varchar",
    length: 150,
    unique: true,
    // ...
})
name: string;
```

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

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

<!-- EN -->
* `type: ColumnType` - Column type. One of the type listed [above](#column-types).

<!-- ZH -->
* `type: ColumnType` - 列类型。[上面](#column-types)列出的类型之一。

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

<!-- ZH -->
* `name: string` - 数据库表中的列名。默认情况下列名由属性名生成。你可以通过指定自己的名称来修改它。

<!-- EN -->
* `length: number` - Column type's length. For example if you want to create `varchar(150)` type you specify column type and length options.

<!-- ZH -->
* `length: number` - 列类型的长度。例如如果你想创建 `varchar(150)` 类型，就要指定列类型和 length 选项。

<!-- EN -->
* `onUpdate: string` - `ON UPDATE` trigger. Used only in [MySQL](https://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html).

<!-- ZH -->
* `onUpdate: string` - `ON UPDATE` 触发器。仅在 [MySQL](https://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html) 中使用。

<!-- EN -->
* `nullable: boolean` - Makes column `NULL` or `NOT NULL` in the database. By default column is `nullable: false`.

<!-- ZH -->
* `nullable: boolean` - 让列在数据库中为 `NULL` 或 `NOT NULL`。默认情况下列是 `nullable: false`。

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

<!-- ZH -->
* `update: boolean` - 表示列值是否会被 "save" 操作更新。如果为 false，你只能在首次插入对象时写入该值。默认值为 `true`。

<!-- EN -->
* `insert: boolean` - Indicates if column value is set the first time you insert the object. Default value is `true`.

<!-- ZH -->
* `insert: boolean` - 表示列值是否在首次插入对象时被设置。默认值为 `true`。

<!-- EN -->
* `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`

<!-- ZH -->
* `select: boolean` - 定义查询时是否默认隐藏该列。设为 `false` 时，标准查询不会返回该列数据。默认情况下列是 `select: true`

<!-- EN -->
* `default: string` - Adds database-level column's `DEFAULT` value.

<!-- ZH -->
* `default: string` - 添加数据库层面的列 `DEFAULT` 值。

<!-- EN -->
* `primary: boolean` - Marks column as primary. Same if you use `@PrimaryColumn`.

<!-- ZH -->
* `primary: boolean` - 把列标记为主键。等同于使用 `@PrimaryColumn`。

<!-- EN -->
* `unique: boolean` - Marks column as unique column (creates unique constraint).

<!-- ZH -->
* `unique: boolean` - 把列标记为唯一列（创建唯一约束）。

<!-- EN -->
* `comment: string` - Database's column comment. Not supported by all database types.

<!-- ZH -->
* `comment: string` - 数据库的列注释。并非所有数据库类型都支持。

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

<!-- ZH -->
* `precision: number` - decimal（精确数值）列的精度（仅适用于 decimal 列），即存储数值时的最大位数。用于某些列类型。

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

<!-- ZH -->
* `scale: number` - decimal（精确数值）列的标度（仅适用于 decimal 列），表示小数点右侧的位数，且不能大于 precision。用于某些列类型。

<!-- EN -->
* `unsigned: boolean` - Puts `UNSIGNED` attribute on to a numeric column. Used only in MySQL.

<!-- ZH -->
* `unsigned: boolean` - 给数值列加上 `UNSIGNED` 属性。仅在 MySQL 中使用。

<!-- EN -->
* `charset: string` - Defines a column character set. Not supported by all database types.

<!-- ZH -->
* `charset: string` - 定义列的字符集。并非所有数据库类型都支持。

<!-- EN -->
* `collation: string` - Defines a column collation.

<!-- ZH -->
* `collation: string` - 定义列的排序规则。

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

<!-- ZH -->
* `enum: string[]|AnyEnum` - 在 `enum` 列类型中用于指定允许的枚举值列表。你可以指定值数组，也可以指定一个枚举类。

<!-- EN -->
* `enumName: string` - Defines the name for the used enum.

<!-- ZH -->
* `enumName: string` - 定义所用枚举的名称。

<!-- EN -->
* `asExpression: string` - Generated column expression. Supported by PostgreSQL/CockroachDB, MySQL/MariaDB, Oracle, SAP HANA, Spanner, SQLite, and SQL Server.

<!-- ZH -->
* `asExpression: string` - 生成列表达式。受 PostgreSQL/CockroachDB、MySQL/MariaDB、Oracle、SAP HANA、Spanner、SQLite 和 SQL Server 支持。

<!-- EN -->
* `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`).

<!-- ZH -->
* `generatedType: "VIRTUAL"|"STORED"` - 生成列类型。受 PostgreSQL（仅 `STORED`）、CockroachDB、MySQL/MariaDB、Oracle（仅 `VIRTUAL`）、Spanner（仅 `STORED`）、SQLite 和 SQL Server（仅 `STORED`，内部映射为 `PERSISTED`）支持。

<!-- EN -->
* `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).

<!-- ZH -->
* `hstoreType: "object"|"string"` - `HSTORE` 列的返回类型。以字符串或对象形式返回值。仅在 [Postgres](https://www.postgresql.org/docs/9.6/static/hstore.html) 中使用。

<!-- EN -->
* `array: boolean` - Used for postgres and cockroachdb column types which can be array (for example int\[])

<!-- ZH -->
* `array: boolean` - 用于 postgres 和 cockroachdb 中可以为数组的列类型（例如 int\[]）

<!-- EN -->
* `transformer: { from(value: DatabaseType): EntityType, to(value: EntityType): DatabaseType }` - Used to marshal properties of arbitrary type `EntityType` into a type `DatabaseType` supported by the database. Array of transformers are also supported and will be applied in natural order when writing, and in reverse order when reading. e.g. `[lowercase, encrypt]` will first lowercase the string then encrypt it when writing, and will decrypt then do nothing when reading.

<!-- ZH -->
* `transformer: { from(value: DatabaseType): EntityType, to(value: EntityType): DatabaseType }` - 用于把任意类型 `EntityType` 的属性编组为数据库所支持的 `DatabaseType` 类型。也支持转换器数组，写入时按自然顺序应用，读取时按相反顺序应用。例如 `[lowercase, encrypt]` 在写入时会先把字符串转小写再加密，读取时会先解密然后不做处理。

<!-- EN -->
* `utc: boolean` - Indicates if date values should be stored and retrieved in UTC timezone instead of local timezone. Only applies to `date` column type. Default value is `false` (uses local timezone for backward compatibility).

<!-- ZH -->
* `utc: boolean` - 表示日期值是否应以 UTC 时区而非本地时区存储和读取。仅适用于 `date` 列类型。默认值为 `false`（出于向后兼容使用本地时区）。

<!-- EN -->
Note: most of those column options are RDBMS-specific and aren't available in `MongoDB`.

<!-- ZH -->
注意：这些列选项大多是 RDBMS 专属的，在 `MongoDB` 中不可用。

<!-- EN -->
## Entity inheritance

<!-- ZH -->
## 实体继承

<!-- EN -->
You can reduce duplication in your code by using entity inheritance.

<!-- ZH -->
你可以通过使用实体继承来减少代码重复。

<!-- EN -->
For example, you have `Photo`, `Question`, `Post` entities:

<!-- ZH -->
例如，你有 `Photo`、`Question`、`Post` 这几个实体：

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

    @Column()
    title: string

    @Column()
    description: string

    @Column()
    size: string
}

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

    @Column()
    title: string

    @Column()
    description: string

    @Column()
    answersCount: number
}

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

    @Column()
    title: string

    @Column()
    description: string

    @Column()
    viewCount: number
}
```

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

    @Column()
    title: string

    @Column()
    description: string

    @Column()
    size: string
}

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

    @Column()
    title: string

    @Column()
    description: string

    @Column()
    answersCount: number
}

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

    @Column()
    title: string

    @Column()
    description: string

    @Column()
    viewCount: number
}
```

<!-- EN -->
As you can see all those entities have common columns: `id`, `title`, `description`. To reduce duplication and produce a better abstraction we can create a base class called `Content` for them:

<!-- ZH -->
如你所见，这些实体都有公共列：`id`、`title`、`description`。为了减少重复并得到更好的抽象，我们可以为它们创建一个名为 `Content` 的基类：

<!-- EN -->
```typescript
export abstract class Content {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    title: string

    @Column()
    description: string
}
@Entity()
export class Photo extends Content {
    @Column()
    size: string
}

@Entity()
export class Question extends Content {
    @Column()
    answersCount: number
}

@Entity()
export class Post extends Content {
    @Column()
    viewCount: number
}
```

<!-- ZH -->
```typescript
export abstract class Content {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    title: string

    @Column()
    description: string
}
@Entity()
export class Photo extends Content {
    @Column()
    size: string
}

@Entity()
export class Question extends Content {
    @Column()
    answersCount: number
}

@Entity()
export class Post extends Content {
    @Column()
    viewCount: number
}
```

<!-- EN -->
All columns (relations, embeds, etc.) from parent entities (parent can extend other entity as well) will be inherited and created in final entities.

<!-- ZH -->
父实体（父类也可以继续继承其他实体）的所有列（关系、嵌入等）都会被继承，并在最终实体中创建。

<!-- EN -->
## Tree entities

<!-- ZH -->
## 树形实体

<!-- EN -->
TypeORM supports the Adjacency list and Closure table patterns of storing tree structures.

<!-- ZH -->
TypeORM 支持邻接表（Adjacency list）和闭包表（Closure table）两种存储树形结构的模式。

<!-- EN -->
### Adjacency list

<!-- ZH -->
### 邻接表

<!-- EN -->
Adjacency list is a simple model with self-referencing. Benefit of this approach is simplicity, drawback is you can't load a big tree at once because of join limitations. Example:

<!-- ZH -->
邻接表是一种带自引用的简单模型。这种方式的优点是简单，缺点是受连接限制，你无法一次性加载一棵大树。示例：

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

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

    @Column()
    name: string

    @Column()
    description: string

    @ManyToOne((type) => Category, (category) => category.children)
    parent: Category

    @OneToMany((type) => Category, (category) => category.parent)
    children: Category[]
}
```

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

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

    @Column()
    name: string

    @Column()
    description: string

    @ManyToOne((type) => Category, (category) => category.children)
    parent: Category

    @OneToMany((type) => Category, (category) => category.parent)
    children: Category[]
}
```

<!-- EN -->
### Closure table

<!-- ZH -->
### 闭包表

<!-- EN -->
A closure table stores relations between parent and child in a separate table in a special way. It's efficient in both reads and writes. To learn more about closure table take a look at [this awesome presentation by Bill Karwin](https://www.slideshare.net/billkarwin/models-for-hierarchical-data). Example:

<!-- ZH -->
闭包表以特殊方式把父子关系存在一张单独的表里。它在读和写两方面都很高效。要进一步了解闭包表，可以看看 [Bill Karwin 的这份精彩演示](https://www.slideshare.net/billkarwin/models-for-hierarchical-data)。示例：

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

@Entity()
@Tree("closure-table")
export class Category {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @Column()
    description: string

    @TreeChildren()
    children: Category[]

    @TreeParent()
    parent: Category

    @TreeLevelColumn()
    level: number
}
```

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

@Entity()
@Tree("closure-table")
export class Category {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @Column()
    description: string

    @TreeChildren()
    children: Category[]

    @TreeParent()
    parent: Category

    @TreeLevelColumn()
    level: number
}
```
