跳至主内容区

分离实体定义

非官方测试版翻译

本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →

定义模式

您可以直接在模型中使用装饰器定义实体及其列。 但有些人更倾向于在单独文件中定义实体及其列, 这些文件在 TypeORM 中称为"实体模式"。

简单定义示例:

import { EntitySchema } from "typeorm"

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

关联关系示例:

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
},
},
})

复杂示例:

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"],
},
],
})

若需确保实体类型安全,可定义模型并在模式定义中指定:

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,
},
},
})

扩展模式

使用Decorator方法时,可以轻松将基本列extend到抽象类并直接继承。 例如,您的idcreatedAtupdatedAt列可在BaseEntity中定义。更多细节请参阅 具体表继承文档。

使用EntitySchema方法时无法直接继承,但可利用Spread Operator(展开运算符 ...)实现类似效果。

重新考虑前文的Category示例。您可能需要extract基础列描述并在其他模式中复用:

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,
}

现在您可以在其他模式模型中这样使用BaseColumnSchemaPart

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,
},
},
})

您可以在模式模型中使用嵌入式实体:

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_",
},
},
})

请确保将extended列也添加到Category接口中(例如通过export interface Category extend BaseEntity)。

单表继承

要使用单表继承

  1. 父类模式中添加inheritance选项,指定继承模式("STI")和 鉴别器列(该列将存储每行的_子类_名称)

  2. 为所有子类模式设置type: "entity-child"选项,同时使用前述展开运算符语法 扩展_父类_列

// 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()
}
}
// 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,
},
},
})

使用模式查询/插入数据

当然,您可以在存储库或实体管理器中使用已定义的模式,就像使用装饰器一样。 参考前文定义的Category示例(包含其InterfaceCategoryEntity模式), 即可获取数据或操作数据库。

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