# 分离实体定义

> 英文标题：Separating Entity Definition
> 官网原文：https://typeorm.io/docs/entity/separating-entity-definition
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 29 块

---

<!-- EN -->
# Separating Entity Definition

<!-- ZH -->
# 分离实体定义

<!-- EN -->
## Defining Schemas

<!-- ZH -->
## 定义 Schema

<!-- EN -->
You can define an entity and its columns right in the model, using decorators. But some people prefer to define an entity and its columns inside separate files which are called "entity schemas" in TypeORM.

<!-- ZH -->
你可以用装饰器直接在模型中定义实体及其列。但有些人更喜欢把实体及其列定义在单独的文件里，TypeORM 把这类文件称为"实体 schema"。

<!-- EN -->
Simple definition example:

<!-- ZH -->
简单定义示例：

<!-- EN -->
```ts
import { EntitySchema } from "typeorm"

export const CategoryEntity = new EntitySchema({
    name: "category",
    columns: {
        id: {
            type: Number,
            primary: true,
            generated: true,
        },
        name: {
            type: String,
        },
    },
})
```

<!-- ZH -->
```ts
import { EntitySchema } from "typeorm"

export const CategoryEntity = new EntitySchema({
    name: "category",
    columns: {
        id: {
            type: Number,
            primary: true,
            generated: true,
        },
        name: {
            type: String,
        },
    },
})
```

<!-- EN -->
Example with relations:

<!-- ZH -->
带关系的示例：

<!-- EN -->
```ts
import { EntitySchema } from "typeorm"

export const PostEntity = new EntitySchema({
    name: "post",
    columns: {
        id: {
            type: Number,
            primary: true,
            generated: true,
        },
        title: {
            type: String,
        },
        text: {
            type: String,
        },
    },
    relations: {
        categories: {
            type: "many-to-many",
            target: "category", // CategoryEntity
        },
    },
})
```

<!-- ZH -->
```ts
import { EntitySchema } from "typeorm"

export const PostEntity = new EntitySchema({
    name: "post",
    columns: {
        id: {
            type: Number,
            primary: true,
            generated: true,
        },
        title: {
            type: String,
        },
        text: {
            type: String,
        },
    },
    relations: {
        categories: {
            type: "many-to-many",
            target: "category", // CategoryEntity
        },
    },
})
```

<!-- EN -->
Complex example:

<!-- ZH -->
复杂示例：

<!-- EN -->
```ts
import { EntitySchema } from "typeorm"

export const PersonSchema = new EntitySchema({
    name: "person",
    columns: {
        id: {
            primary: true,
            type: "int",
            generated: "increment",
        },
        firstName: {
            type: String,
            length: 30,
        },
        lastName: {
            type: String,
            length: 50,
            nullable: false,
        },
        age: {
            type: Number,
            nullable: false,
        },
        countryCode: {
            type: String,
            length: 2,
            foreignKey: {
                target: "countries", // CountryEntity
                inverseSide: "code",
            },
        },
        cityId: {
            type: Number,
            foreignKey: {
                target: "cities", // CityEntity
            },
        },
    },
    checks: [
        { expression: `"firstName" <> 'John' AND "lastName" <> 'Doe'` },
        { expression: `"age" > 18` },
    ],
    indices: [
        {
            name: "IDX_TEST",
            unique: true,
            columns: ["firstName", "lastName"],
        },
    ],
    uniques: [
        {
            name: "UNIQUE_TEST",
            columns: ["firstName", "lastName"],
        },
    ],
    foreignKeys: [
        {
            target: "cities", // CityEntity
            columnNames: ["cityId", "countryCode"],
            referencedColumnNames: ["id", "countryCode"],
        },
    ],
})
```

<!-- ZH -->
```ts
import { EntitySchema } from "typeorm"

export const PersonSchema = new EntitySchema({
    name: "person",
    columns: {
        id: {
            primary: true,
            type: "int",
            generated: "increment",
        },
        firstName: {
            type: String,
            length: 30,
        },
        lastName: {
            type: String,
            length: 50,
            nullable: false,
        },
        age: {
            type: Number,
            nullable: false,
        },
        countryCode: {
            type: String,
            length: 2,
            foreignKey: {
                target: "countries", // CountryEntity
                inverseSide: "code",
            },
        },
        cityId: {
            type: Number,
            foreignKey: {
                target: "cities", // CityEntity
            },
        },
    },
    checks: [
        { expression: `"firstName" <> 'John' AND "lastName" <> 'Doe'` },
        { expression: `"age" > 18` },
    ],
    indices: [
        {
            name: "IDX_TEST",
            unique: true,
            columns: ["firstName", "lastName"],
        },
    ],
    uniques: [
        {
            name: "UNIQUE_TEST",
            columns: ["firstName", "lastName"],
        },
    ],
    foreignKeys: [
        {
            target: "cities", // CityEntity
            columnNames: ["cityId", "countryCode"],
            referencedColumnNames: ["id", "countryCode"],
        },
    ],
})
```

<!-- EN -->
If you want to make your entity typesafe, you can define a model and specify it in schema definition:

<!-- ZH -->
如果你想让实体具备类型安全，可以定义一个模型并在 schema 定义中指定它：

<!-- EN -->
```ts
import { EntitySchema } from "typeorm"

export interface Category {
    id: number
    name: string
}

export const CategoryEntity = new EntitySchema<Category>({
    name: "category",
    columns: {
        id: {
            type: Number,
            primary: true,
            generated: true,
        },
        name: {
            type: String,
        },
    },
})
```

<!-- ZH -->
```ts
import { EntitySchema } from "typeorm"

export interface Category {
    id: number
    name: string
}

export const CategoryEntity = new EntitySchema<Category>({
    name: "category",
    columns: {
        id: {
            type: Number,
            primary: true,
            generated: true,
        },
        name: {
            type: String,
        },
    },
})
```

<!-- EN -->
## Extending Schemas

<!-- ZH -->
## 扩展 Schema

<!-- EN -->
When using the `Decorator` approach it is easy to `extend` basic columns to an abstract class and simply extend this. For example, your `id`, `createdAt` and `updatedAt` columns may be defined in such a `BaseEntity`. For more details, see the documentation on [concrete table inheritance](https://typeorm.io/docs/entity/entity-inheritance#concrete-table-inheritance).

<!-- ZH -->
使用 `Decorator` 方式时，很容易把基础列 `extend` 到一个抽象类并直接继承它。例如，你的 `id`、`createdAt` 和 `updatedAt` 列可以定义在这样的 `BaseEntity` 中。更多细节请参阅[具体表继承](https://typeorm.io/docs/entity/entity-inheritance#concrete-table-inheritance)的文档。

<!-- EN -->
When using the `EntitySchema` approach, this is not possible. However, you can use the `Spread Operator` (`...`) to your advantage.

<!-- ZH -->
使用 `EntitySchema` 方式时做不到这一点。不过，你可以利用 `Spread Operator`（`...`）来达到目的。

<!-- EN -->
Reconsider the `Category` example from above. You may want to `extract` basic column descriptions and reuse it across your other schemas. This may be done in the following way:

<!-- ZH -->
重新考虑上面的 `Category` 示例。你可能想把基础列描述`抽取`出来，在其他 schema 中复用。可以这样做：

<!-- EN -->
```ts
import { EntitySchemaColumnOptions } from "typeorm"

export const BaseColumnSchemaPart = {
    id: {
        type: Number,
        primary: true,
        generated: true,
    } as EntitySchemaColumnOptions,
    createdAt: {
        name: "created_at",
        type: "timestamp with time zone",
        createDate: true,
    } as EntitySchemaColumnOptions,
    updatedAt: {
        name: "updated_at",
        type: "timestamp with time zone",
        updateDate: true,
    } as EntitySchemaColumnOptions,
}
```

<!-- ZH -->
```ts
import { EntitySchemaColumnOptions } from "typeorm"

export const BaseColumnSchemaPart = {
    id: {
        type: Number,
        primary: true,
        generated: true,
    } as EntitySchemaColumnOptions,
    createdAt: {
        name: "created_at",
        type: "timestamp with time zone",
        createDate: true,
    } as EntitySchemaColumnOptions,
    updatedAt: {
        name: "updated_at",
        type: "timestamp with time zone",
        updateDate: true,
    } as EntitySchemaColumnOptions,
}
```

<!-- EN -->
Now you can use the `BaseColumnSchemaPart` in your other schema models, like this:

<!-- ZH -->
现在你可以在其他 schema 模型中使用 `BaseColumnSchemaPart`，像这样：

<!-- EN -->
```ts
export const CategoryEntity = new EntitySchema<Category>({
    name: "category",
    columns: {
        ...BaseColumnSchemaPart,
        // the CategoryEntity now has the defined id, createdAt, updatedAt columns!
        // in addition, the following NEW fields are defined
        name: {
            type: String,
        },
    },
})
```

<!-- ZH -->
```ts
export const CategoryEntity = new EntitySchema<Category>({
    name: "category",
    columns: {
        ...BaseColumnSchemaPart,
        // CategoryEntity 现在拥有已定义的 id、createdAt、updatedAt 列！
        // 此外，还定义了下面这些新字段
        name: {
            type: String,
        },
    },
})
```

<!-- EN -->
You can use embedded entities in schema models, like this:

<!-- ZH -->
你可以在 schema 模型中使用嵌入式实体，像这样：

<!-- EN -->
```ts
export interface Name {
    first: string
    last: string
}

export const NameEntitySchema = new EntitySchema<Name>({
    name: "name",
    columns: {
        first: {
            type: "varchar",
        },
        last: {
            type: "varchar",
        },
    },
})

export interface User {
    id: string
    name: Name
    isActive: boolean
}

export const UserEntitySchema = new EntitySchema<User>({
    name: "user",
    columns: {
        id: {
            primary: true,
            generated: "uuid",
            type: "uuid",
        },
        isActive: {
            type: "boolean",
        },
    },
    embeddeds: {
        name: {
            schema: NameEntitySchema,
            prefix: "name_",
        },
    },
})
```

<!-- ZH -->
```ts
export interface Name {
    first: string
    last: string
}

export const NameEntitySchema = new EntitySchema<Name>({
    name: "name",
    columns: {
        first: {
            type: "varchar",
        },
        last: {
            type: "varchar",
        },
    },
})

export interface User {
    id: string
    name: Name
    isActive: boolean
}

export const UserEntitySchema = new EntitySchema<User>({
    name: "user",
    columns: {
        id: {
            primary: true,
            generated: "uuid",
            type: "uuid",
        },
        isActive: {
            type: "boolean",
        },
    },
    embeddeds: {
        name: {
            schema: NameEntitySchema,
            prefix: "name_",
        },
    },
})
```

<!-- EN -->
Be sure to add the `extended` columns also to the `Category` interface (e.g., via `export interface Category extend BaseEntity`).

<!-- ZH -->
务必把`扩展`出来的列也加进 `Category` 接口（例如通过 `export interface Category extend BaseEntity`）。

<!-- EN -->
### Single Table Inheritance

<!-- ZH -->
### 单表继承

<!-- EN -->
In order to use [Single Table Inheritance](https://typeorm.io/docs/entity/entity-inheritance#single-table-inheritance):

<!-- ZH -->
要使用[单表继承](https://typeorm.io/docs/entity/entity-inheritance#single-table-inheritance)：

<!-- EN -->
1. Add the `inheritance` option to the **parent** class schema, specifying the inheritance pattern ("STI") and the **discriminator** column, which will store the name of the *child* class on each row
2. Set the `type: "entity-child"` option for all **children** classes' schemas, while extending the *parent* class columns using the spread operator syntax described above

<!-- ZH -->
1. 给 **父** 类的 schema 加上 `inheritance` 选项，指定继承模式（"STI"）和 **鉴别器（discriminator）** 列，该列会在每一行中存放*子*类的名称
2. 为所有 **子** 类的 schema 设置 `type: "entity-child"` 选项，同时用上面描述的展开运算符语法继承*父*类的列

<!-- EN -->
```ts
// entity.ts

export abstract class Base {
    id!: number
    type!: string
    createdAt!: Date
    updatedAt!: Date
}

export class A extends Base {
    constructor(public a: boolean) {
        super()
    }
}

export class B extends Base {
    constructor(public b: number) {
        super()
    }
}

export class C extends Base {
    constructor(public c: string) {
        super()
    }
}
```

<!-- ZH -->
```ts
// entity.ts

export abstract class Base {
    id!: number
    type!: string
    createdAt!: Date
    updatedAt!: Date
}

export class A extends Base {
    constructor(public a: boolean) {
        super()
    }
}

export class B extends Base {
    constructor(public b: number) {
        super()
    }
}

export class C extends Base {
    constructor(public c: string) {
        super()
    }
}
```

<!-- EN -->
```ts
// schema.ts

const BaseSchema = new EntitySchema<Base>({
    target: Base,
    name: "Base",
    columns: {
        id: {
            type: Number,
            primary: true,
            generated: "increment",
        },
        type: {
            type: String,
        },
        createdAt: {
            type: Date,
            createDate: true,
        },
        updatedAt: {
            type: Date,
            updateDate: true,
        },
    },
    // NEW: Inheritance options
    inheritance: {
        pattern: "STI",
        column: "type",
    },
})

const ASchema = new EntitySchema<A>({
    target: A,
    name: "A",
    type: "entity-child",
    // When saving instances of 'A', the "type" column will have the value
    // specified on the 'discriminatorValue' property
    discriminatorValue: "my-custom-discriminator-value-for-A",
    columns: {
        ...BaseSchema.options.columns,
        a: {
            type: Boolean,
        },
    },
})

const BSchema = new EntitySchema<B>({
    target: B,
    name: "B",
    type: "entity-child",
    discriminatorValue: undefined, // Defaults to the class name (e.g. "B")
    columns: {
        ...BaseSchema.options.columns,
        b: {
            type: Number,
        },
    },
})

const CSchema = new EntitySchema<C>({
    target: C,
    name: "C",
    type: "entity-child",
    discriminatorValue: "my-custom-discriminator-value-for-C",
    columns: {
        ...BaseSchema.options.columns,
        c: {
            type: String,
        },
    },
})
```

<!-- ZH -->
```ts
// schema.ts

const BaseSchema = new EntitySchema<Base>({
    target: Base,
    name: "Base",
    columns: {
        id: {
            type: Number,
            primary: true,
            generated: "increment",
        },
        type: {
            type: String,
        },
        createdAt: {
            type: Date,
            createDate: true,
        },
        updatedAt: {
            type: Date,
            updateDate: true,
        },
    },
    // 新增：继承选项
    inheritance: {
        pattern: "STI",
        column: "type",
    },
})

const ASchema = new EntitySchema<A>({
    target: A,
    name: "A",
    type: "entity-child",
    // 保存 'A' 的实例时，"type" 列的值将是
    // 'discriminatorValue' 属性上指定的值
    discriminatorValue: "my-custom-discriminator-value-for-A",
    columns: {
        ...BaseSchema.options.columns,
        a: {
            type: Boolean,
        },
    },
})

const BSchema = new EntitySchema<B>({
    target: B,
    name: "B",
    type: "entity-child",
    discriminatorValue: undefined, // 默认为类名（例如 "B"）
    columns: {
        ...BaseSchema.options.columns,
        b: {
            type: Number,
        },
    },
})

const CSchema = new EntitySchema<C>({
    target: C,
    name: "C",
    type: "entity-child",
    discriminatorValue: "my-custom-discriminator-value-for-C",
    columns: {
        ...BaseSchema.options.columns,
        c: {
            type: String,
        },
    },
})
```

<!-- EN -->
## Using Schemas to Query / Insert Data

<!-- ZH -->
## 使用 Schema 查询 / 插入数据

<!-- EN -->
Of course, you can use the defined schemas in your repositories or entity manager as you would use the decorators. Consider the previously defined `Category` example (with its `Interface` and `CategoryEntity` schema) in order to get some data or manipulate the database.

<!-- ZH -->
当然，你可以在 repository 或 entity manager 中像使用装饰器那样使用已定义的 schema。考虑前面定义的 `Category` 示例（及其 `Interface` 和 `CategoryEntity` schema），用它来获取数据或操作数据库。

<!-- EN -->
```ts
// request data
const categoryRepository = dataSource.getRepository<Category>(CategoryEntity)
const category = await categoryRepository.findOneBy({
    id: 1,
}) // category is properly typed!

// insert a new category into the database
const categoryDTO = {
    // note that the ID is autogenerated; see the schema above
    name: "new category",
}
const newCategory = await categoryRepository.save(categoryDTO)
```

<!-- ZH -->
```ts
// 查询数据
const categoryRepository = dataSource.getRepository<Category>(CategoryEntity)
const category = await categoryRepository.findOneBy({
    id: 1,
}) // category 具备正确的类型！

// 向数据库插入一个新分类
const categoryDTO = {
    // 注意 ID 是自动生成的；参见上面的 schema
    name: "new category",
}
const newCategory = await categoryRepository.save(categoryDTO)
```
