装饰器参考
实体装饰器
@Entity
把你的模型标记为实体。实体是一个会被转换成数据库表的类。你可以在实体中指定表名:
@Entity("users")
export class User {}这段代码会创建一张名为 "users" 的数据库表。
你也可以指定一些额外的实体选项:
name- 表名。如果不指定,表名会由实体类名生成。database- 所选数据库服务器中的数据库名。schema- 模式名。comment- 数据库表注释。并非所有数据库类型都支持。目前 MySQL、MariaDB、PostgreSQL、SAP HANA 支持。engine- 建表时要设置的数据库引擎(仅在部分数据库中有效)。synchronize- 用false标记的实体会在结构更新中被跳过。orderBy- 指定使用find操作和QueryBuilder时实体的默认排序。
示例:
@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 {}进一步了解实体。
@ViewEntity
视图实体是一个映射到数据库视图的类。
@ViewEntity() 接受以下选项:
name- 视图名称。如果不指定,视图名称会由实体类名生成。database- 所选数据库服务器中的数据库名。schema- 模式名。expression- 视图定义。必填参数。
expression 可以是一个字符串,其中的列和表已按所用数据库正确转义(示例中为 postgres):
@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 {}也可以是一个 QueryBuilder 实例
@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 {}注意: 受驱动限制,不支持参数绑定。请改用字面量参数。
@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 {}进一步了解视图实体。
列装饰器
@Column
把你实体中的一个属性标记为表列。示例:
@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
}@Column 接受若干你可以使用的选项:
type: ColumnType- 列类型。受支持的列类型之一。name: string- 数据库表中的列名。默认情况下,列名由属性名生成。你可以通过指定自己的名称来修改它。length: string|number- 列类型的长度。例如,如果你想创建varchar(150)类型,就要指定列类型和 length 选项。width: number- 列类型的显示宽度。仅用于 MySQL 整数类型。在较新的 MySQL 版本中已弃用,将在 TypeORM 的后续版本中移除。onUpdate: string-ON UPDATE触发器。仅在 MySQL 中使用。nullable: boolean- 决定该列是否可以变成NULL,还是必须始终是NOT NULL。默认情况下列是nullable: false。update: boolean- 表示列值是否会被 "save" 操作更新。如果为 false,你只能在首次插入对象时写入该值。默认值为true。insert: boolean- 表示列值是否在首次插入对象时被设置。默认值为true。select: boolean- 定义查询时是否默认隐藏该列。设为false时,标准查询不会返回该列数据。默认情况下列是select: truedefault: 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 中使用。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,用作空间列上的约束。如果不指定,默认为0。标准地理坐标(WGS84 基准下的经纬度)对应 EPSG 4326。仅在 PostgreSQL 和 CockroachDB 中使用。
进一步了解实体列。
@PrimaryColumn
把你实体中的一个属性标记为表的主键列。与 @Column 装饰器相同,但把它的 primary 选项设为 true。
示例:
@Entity()
export class User {
@PrimaryColumn()
id: number
}@PrimaryColumn() 支持自定义主键约束名:
@Entity()
export class User {
@PrimaryColumn({ primaryKeyConstraintName: "pk_user_id" })
id: number
}注意:把
primaryKeyConstraintName与多个主键一起使用时,所有主键列的约束名必须相同。
进一步了解实体列。
@PrimaryGeneratedColumn
把你实体中的一个属性标记为由表生成的主键列。它创建的列是主键,且其值自动生成。示例:
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
}@PrimaryGeneratedColumn() 支持自定义主键约束名:
@Entity()
export class User {
@PrimaryGeneratedColumn({ primaryKeyConstraintName: "pk_user_id" })
id: number
}共有四种生成策略:
increment- 使用 AUTO_INCREMENT / SERIAL / SEQUENCE(取决于数据库类型)生成递增数字。identity- 仅适用于 PostgreSQL 10+。10 以上的 Postgres 版本支持符合 SQL 标准的 IDENTITY 列。当把生成策略标记为identity时,该列会使用GENERATED [ALWAYS|BY DEFAULT] AS IDENTITY创建uuid- 生成唯一的uuid字符串。rowid- 仅适用于 CockroachDB。值会使用unique_rowid()函数自动生成。该函数根据当前时间戳和执行INSERT或UPSERT操作的节点 ID 生成一个 64 位整数。注意:使用
rowid生成策略的属性必须是string数据类型
默认生成策略是 increment,要改成其他策略,只需把它作为第一个参数传给装饰器:
@Entity()
export class User {
@PrimaryGeneratedColumn("uuid")
id: string
}进一步了解实体列。
@ObjectIdColumn
把你实体中的一个属性标记为 ObjectId。该装饰器仅用于 MongoDB。MongoDB 中的每个实体都必须有一个 ObjectId 列。示例:
@Entity()
export class User {
@ObjectIdColumn()
id: ObjectId
}进一步了解 MongoDB。
@CreateDateColumn
特殊列,会被自动设置为实体的插入时间。你不需要往这一列里写值——它会被自动设置。示例:
@Entity()
export class User {
@CreateDateColumn()
createdDate: Date
}@UpdateDateColumn
特殊列,每次你调用 entity manager 或 repository 的 save 时,它都会被自动设置为实体的更新时间。你不需要往这一列里写值——它会被自动设置。
当 upsert 操作因冲突而发生更新时,这一列也会被自动更新。
@Entity()
export class User {
@UpdateDateColumn()
updatedDate: Date
}@DeleteDateColumn
特殊列,每次你调用 entity manager 或 repository 的软删除时,它都会被自动设置为实体的删除时间。你不需要设置这一列——它会被自动设置。
TypeORM 自身的软删除功能利用全局作用域,只从数据库中取出"未删除"的实体。
如果设置了 @DeleteDateColumn,默认作用域将是"未删除"。
@Entity()
export class User {
@DeleteDateColumn()
deletedDate: Date
}@VersionColumn
特殊列,每次你调用 entity manager 或 repository 的 save 时,它都会被自动设置为实体的版本号(递增数字)。你不需要往这一列里写值——它会被自动设置。
当 upsert 操作因冲突而发生更新时,这一列也会被自动更新。
@Entity()
export class User {
@VersionColumn()
version: number
}@Generated
把列标记为生成值。例如:
@Entity()
export class User {
@Column()
@Generated("uuid")
uuid: string
}值只会生成一次,在把实体插入数据库之前。
@VirtualColumn
特殊列,它永远不会被保存到数据库,因此表现得像只读属性。每次你调用 entity manager 的 find 或 findOne 时,该值都会根据 VirtualColumn 装饰器中提供的查询函数重新计算。传给查询的 alias 参数引用的是幕后所生成查询中该实体的确切别名。
@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
}关系装饰器
@OneToOne
一对一是一种 A 只包含一个 B 实例、且 B 只包含一个 A 实例的关系。以 User 和 Profile 实体为例。一个用户只能有一个档案,而一个档案只属于一个用户。示例:
import { Entity, OneToOne, JoinColumn } from "typeorm"
import { Profile } from "./Profile"
@Entity()
export class User {
@OneToOne((type) => Profile, (profile) => profile.user)
@JoinColumn()
profile: Profile
}进一步了解一对一关系。
@ManyToOne
多对一 / 一对多是一种 A 包含多个 B 实例、但 B 只包含一个 A 实例的关系。以 User 和 Photo 实体为例。一个用户可以有多张照片,但每张照片只属于一个用户。示例:
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
}进一步了解多对一 / 一对多关系。
@OneToMany
多对一 / 一对多是一种 A 包含多个 B 实例、但 B 只包含一个 A 实例的关系。以 User 和 Photo 实体为例。一个用户可以有多张照片,但每张照片只属于一个用户。示例:
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[]
}进一步了解多对一 / 一对多关系。
@ManyToMany
多对多是一种 A 包含多个 B 实例、且 B 也包含多个 A 实例的关系。以 Question 和 Category 实体为例。一个问题可以属于多个分类,而每个分类可以包含多个问题。示例:
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[]
}进一步了解多对多关系。
@JoinColumn
定义关系的哪一侧持有带外键的连接列,并允许你自定义连接列名、被引用列名和外键名。示例:
@Entity()
export class Post {
@ManyToOne((type) => Category)
@JoinColumn({
name: "cat_id",
referencedColumnName: "name",
foreignKeyConstraintName: "fk_cat_id",
})
category: Category
}@JoinTable
用于 many-to-many 关系,描述"中间表"的连接列。中间表是 TypeORM 自动创建的一张特殊独立表,其中的列引用相关联的实体。你可以修改生成的"中间表"的表名、中间表中的列名、它们通过 joinColumn 与 inverseJoinColumn 属性引用的列,以及所创建的外键名。你也可以把 synchronize 参数设为 false 来跳过结构更新(与 @Entity 中一样)
示例:
@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[]
}如果目标表有复合主键,那么必须给 @JoinTable 装饰器传入一个属性数组。
@RelationId
把特定关系的 id(或多个 id)加载到属性中。例如,如果你的 Post 实体中有一个多对一的 category,你可以通过用 @RelationId 标记一个新属性来获得一个新的分类 id。示例:
@Entity()
export class Post {
@ManyToOne((type) => Category)
category: Category
@RelationId((post: Post) => post.category) // 你需要指定目标关系
categoryId: number
}该功能适用于所有类型的关系,包括 many-to-many:
@Entity()
export class Post {
@ManyToMany((type) => Category)
categories: Category[]
@RelationId((post: Post) => post.categories)
categoryIds: number[]
}关系 id 仅用于展示。修改该值不会添加 / 移除 / 改变底层关系。
订阅者与监听器装饰器
@AfterLoad
你可以在实体中定义一个任意名称的方法并用 @AfterLoad 标记它,每当该实体通过 QueryBuilder 或 repository/manager 的 find 方法被加载时,TypeORM 都会调用它。示例:
@Entity()
export class Post {
@AfterLoad()
updateCounters() {
if (this.likesCount === undefined) this.likesCount = 0
}
}进一步了解监听器。
@BeforeInsert
你可以在实体中定义一个任意名称的方法并用 @BeforeInsert 标记它,TypeORM 会在该实体通过 repository/manager 的 save 被插入之前调用它。示例:
@Entity()
export class Post {
@BeforeInsert()
updateDates() {
this.createdDate = new Date()
}
}进一步了解监听器。
@AfterInsert
你可以在实体中定义一个任意名称的方法并用 @AfterInsert 标记它,TypeORM 会在该实体通过 repository/manager 的 save 被插入之后调用它。示例:
@Entity()
export class Post {
@AfterInsert()
resetCounters() {
this.counters = 0
}
}进一步了解监听器。
@BeforeUpdate
你可以在实体中定义一个任意名称的方法并用 @BeforeUpdate 标记它,TypeORM 会在已有实体通过 repository/manager 的 save 被更新之前调用它。示例:
@Entity()
export class Post {
@BeforeUpdate()
updateDates() {
this.updatedDate = new Date()
}
}进一步了解监听器。
@AfterUpdate
你可以在实体中定义一个任意名称的方法并用 @AfterUpdate 标记它,TypeORM 会在已有实体通过 repository/manager 的 save 被更新之后调用它。示例:
@Entity()
export class Post {
@AfterUpdate()
updateCounters() {
this.counter = 0
}
}进一步了解监听器。
@BeforeRemove
你可以在实体中定义一个任意名称的方法并用 @BeforeRemove 标记它,TypeORM 会在该实体通过 repository/manager 的 remove 被移除之前调用它。示例:
@Entity()
export class Post {
@BeforeRemove()
updateStatus() {
this.status = "removed"
}
}进一步了解监听器。
@AfterRemove
你可以在实体中定义一个任意名称的方法并用 @AfterRemove 标记它,TypeORM 会在该实体通过 repository/manager 的 remove 被移除之后调用它。示例:
@Entity()
export class Post {
@AfterRemove()
updateStatus() {
this.status = "removed"
}
}进一步了解监听器。
@BeforeSoftRemove
你可以在实体中定义一个任意名称的方法并用 @BeforeSoftRemove 标记它,TypeORM 会在该实体通过 repository/manager 的 softRemove 被软删除之前调用它。示例:
@Entity()
export class Post {
@BeforeSoftRemove()
updateStatus() {
this.status = "soft-removed"
}
}进一步了解监听器。
@AfterSoftRemove
你可以在实体中定义一个任意名称的方法并用 @AfterSoftRemove 标记它,TypeORM 会在该实体通过 repository/manager 的 softRemove 被软删除之后调用它。示例:
@Entity()
export class Post {
@AfterSoftRemove()
updateStatus() {
this.status = "soft-removed"
}
}进一步了解监听器。
@BeforeRecover
你可以在实体中定义一个任意名称的方法并用 @BeforeRecover 标记它,TypeORM 会在该实体通过 repository/manager 的 recover 被恢复之前调用它。示例:
@Entity()
export class Post {
@BeforeRecover()
updateStatus() {
this.status = "recovered"
}
}进一步了解监听器。
@AfterRecover
你可以在实体中定义一个任意名称的方法并用 @AfterRecover 标记它,TypeORM 会在该实体通过 repository/manager 的 recover 被恢复之后调用它。示例:
@Entity()
export class Post {
@AfterRecover()
updateStatus() {
this.status = "recovered"
}
}进一步了解监听器。
@EventSubscriber
把一个类标记为事件订阅者,它可以监听特定实体的事件或任意实体的事件。事件通过 QueryBuilder 和 repository/manager 方法触发。示例:
@EventSubscriber()
export class PostSubscriber implements EntitySubscriberInterface<Post> {
/**
* 表示该订阅者只监听 Post 事件。
*/
listenTo() {
return Post
}
/**
* 在 post 插入之前调用。
*/
beforeInsert(event: InsertEvent<Post>) {
console.log(`BEFORE POST INSERTED: `, event.entity)
}
}你可以实现 EntitySubscriberInterface 中的任意方法。要监听任意实体,只需省略 listenTo 方法并使用 any:
@EventSubscriber()
export class PostSubscriber implements EntitySubscriberInterface {
/**
* 在实体插入之前调用。
*/
beforeInsert(event: InsertEvent<any>) {
console.log(`BEFORE ENTITY INSERTED: `, event.entity)
}
}进一步了解订阅者。
其他装饰器
@Index
该装饰器让你可以为特定的一个或多个列创建数据库索引。它也让你能把一个或多个列标记为唯一。该装饰器可以应用在列上,也可以应用在实体本身。当需要单列索引时把它用在列上,当需要跨多列的单个索引时把它用在实体上。示例:
@Entity()
export class User {
@Index()
@Column()
firstName: string
@Index({ unique: true })
@Column()
lastName: string
}@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
}进一步了解索引。
@Unique
该装饰器让你可以为特定的一个或多个列创建数据库唯一约束。该装饰器只能应用在实体本身。你必须把实体字段名(而不是数据库列名)作为参数传入。
示例:
@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
}注意:MySQL 把唯一约束存储为唯一索引
@Check
该装饰器让你可以为特定的一个或多个列创建数据库检查约束。该装饰器只能应用在实体本身。
示例:
@Entity()
@Check(`"firstName" <> 'John' AND "lastName" <> 'Doe'`)
@Check(`"age" > 18`)
export class User {
@Column()
firstName: string
@Column()
lastName: string
@Column()
age: number
}注意:MySQL 不支持检查约束。
@Exclusion
该装饰器让你可以为特定的一个或多个列创建数据库排他约束。该装饰器只能应用在实体本身。
示例:
@Entity()
@Exclusion(`USING gist ("room" WITH =, tsrange("from", "to") WITH &&)`)
export class RoomBooking {
@Column()
room: string
@Column()
from: Date
@Column()
to: Date
}注意:只有 PostgreSQL 支持排他约束。
@ForeignKey
该装饰器让你可以为特定的一个或多个列创建数据库外键。该装饰器可以应用在列上,也可以应用在实体本身。当需要单列外键时把它用在列上,当需要跨多列的单个外键时把它用在实体上。
注意:不要把该装饰器与关系一起使用。 用关系装饰器(
@ManyToOne、@OneToOne等)定义的关系会自动创建外键。只有当你不想定义等价的实体关系、却仍想在数据库中创建外键时,才应使用@ForeignKey装饰器。
示例:
@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
}@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
}@Entity("countries")
export class Country {
@PrimaryColumn({ length: 2 })
code: string
@Column()
name: string
}@Entity("users")
export class User {
@PrimaryColumn({ name: "ref" })
id: number
@Column("uuid", { unique: true })
uuid: string
}Entity decorators
@Entity
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:
@Entity("users")
export class User {}This code will create a database table named "users".
You can also specify some additional entity options:
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 withfalseare skipped from schema updates.orderBy- specifies default ordering for entities when usingfindoperations andQueryBuilder.
Example:
@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 {}Learn more about Entities.
@ViewEntity
View entity is a class that maps to a database view.
@ViewEntity() accepts following options:
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.
expression can be string with properly escaped columns and tables, depend on database used (postgres in example):
@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 {}or an instance of QueryBuilder
@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 {}Note: parameter binding is not supported due to drivers limitations. Use the literal parameters instead.
@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 {}Learn more about View Entities.
Column decorators
@Column
Marks a property in your entity as a table column. Example:
@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
}@Column accept several options you can use:
type: ColumnType- Column type. One of the supported 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 createvarchar(150)type you specify column type and length options.width: number- column type's display width. Used only for MySQL integer types. Deprecated in newer MySQL versions, will be removed from TypeORM in an upcoming version.onUpdate: string-ON UPDATEtrigger. Used only in MySQL.nullable: boolean- determines whether the column can becomeNULLor always has to beNOT NULL. By default column isnullable: 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 istrue.insert: boolean- Indicates if column value is set the first time you insert the object. Default value istrue.select: boolean- Defines whether or not to hide this column by default when making queries. When set tofalse, the column data will not show with a standard query. By default column isselect: truedefault: string- Adds database-level column'sDEFAULTvalue.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- PutsZEROFILLattribute on to a numeric column. Used only in MySQL. Iftrue, MySQL automatically adds theUNSIGNEDattribute to this column. Deprecated in newer MySQL versions, will be removed from TypeORM in an upcoming version. Use a character column and theLPADfunction as suggested by MySQL.unsigned: boolean- PutsUNSIGNEDattribute 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 inenumcolumn 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 (STOREDonly), CockroachDB, MySQL/MariaDB, Oracle (VIRTUALonly), Spanner (STOREDonly), SQLite, and SQL Server (STOREDonly, internally mapped toPERSISTED).hstoreType: "object"|"string"- Return type ofHSTOREcolumn. Returns value as string or as object. Used only in Postgres.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 aZ,MorZMdimensional suffix (PointZ,GeometryZM). If not specified, it will behave as thoughGeometrywas provided. Used only in PostgreSQL and CockroachDB.srid: number- Optional Spatial Reference ID used as a constraint on a spatial column. If not specified, it will default to0. Standard geographic coordinates (latitude/longitude in the WGS84 datum) correspond to EPSG 4326. Used only in PostgreSQL and CockroachDB.
Learn more about entity columns.
@PrimaryColumn
Marks a property in your entity as a table primary column. Same as @Column decorator but sets its primary option to true.
Example:
@Entity()
export class User {
@PrimaryColumn()
id: number
}@PrimaryColumn() supports custom primary key constraint name:
@Entity()
export class User {
@PrimaryColumn({ primaryKeyConstraintName: "pk_user_id" })
id: number
}Note: when using
primaryKeyConstraintNamewith multiple primary keys, the constraint name must be the same for all primary columns.
Learn more about entity columns.
@PrimaryGeneratedColumn
Marks a property in your entity as a table-generated primary column. Column it creates is primary and its value is auto-generated. Example:
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
}@PrimaryGeneratedColumn() supports custom primary key constraint name:
@Entity()
export class User {
@PrimaryGeneratedColumn({ primaryKeyConstraintName: "pk_user_id" })
id: number
}There are four generation strategies:
increment- uses AUTO_INCREMENT / SERIAL / SEQUENCE (depend on database type) to generate incremental number.identity- only for PostgreSQL 10+. Postgres versions above 10 support the SQL-Compliant IDENTITY column. When marking the generation strategy asidentitythe column will be produced usingGENERATED [ALWAYS|BY DEFAULT] AS IDENTITYuuid- generates uniqueuuidstring.rowid- only for CockroachDB. Value is automatically generated using theunique_rowid()function. This produces a 64-bit integer from the current timestamp and ID of the node executing theINSERTorUPSERToperation.Note: property with a
rowidgeneration strategy must be astringdata type
Default generation strategy is increment, to change it to another strategy, simply pass it as the first argument to decorator:
@Entity()
export class User {
@PrimaryGeneratedColumn("uuid")
id: string
}Learn more about entity columns.
@ObjectIdColumn
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:
@Entity()
export class User {
@ObjectIdColumn()
id: ObjectId
}Learn more about MongoDB.
@CreateDateColumn
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:
@Entity()
export class User {
@CreateDateColumn()
createdDate: Date
}@UpdateDateColumn
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.
This column is also automatically updated during upsert operations when an update occurs due to a conflict.
@Entity()
export class User {
@UpdateDateColumn()
updatedDate: Date
}@DeleteDateColumn
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.
TypeORM's own soft delete functionality utilizes global scopes to only pull "non-deleted" entities from the database.
If the @DeleteDateColumn is set, the default scope will be "non-deleted".
@Entity()
export class User {
@DeleteDateColumn()
deletedDate: Date
}@VersionColumn
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.
This column is also automatically updated during upsert operations when an update occurs due to a conflict.
@Entity()
export class User {
@VersionColumn()
version: number
}@Generated
Marks column to be a generated value. For example:
@Entity()
export class User {
@Column()
@Generated("uuid")
uuid: string
}Value will be generated only once, before inserting the entity into the database.
@VirtualColumn
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.
@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
}Relation decorators
@OneToOne
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:
import { Entity, OneToOne, JoinColumn } from "typeorm"
import { Profile } from "./Profile"
@Entity()
export class User {
@OneToOne((type) => Profile, (profile) => profile.user)
@JoinColumn()
profile: Profile
}Learn more about one-to-one relations.
@ManyToOne
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:
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
}Learn more about many-to-one / one-to-many relations.
@OneToMany
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:
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[]
}Learn more about many-to-one / one-to-many relations.
@ManyToMany
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:
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[]
}Learn more about many-to-many relations.
@JoinColumn
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:
@Entity()
export class Post {
@ManyToOne((type) => Category)
@JoinColumn({
name: "cat_id",
referencedColumnName: "name",
foreignKeyConstraintName: "fk_cat_id",
})
category: Category
}@JoinTable
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)
Example:
@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[]
}If the destination table has composite primary keys, then an array of properties must be sent to the @JoinTable decorator.
@RelationId
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:
@Entity()
export class Post {
@ManyToOne((type) => Category)
category: Category
@RelationId((post: Post) => post.category) // you need to specify target relation
categoryId: number
}This functionality works for all kind of relations, including many-to-many:
@Entity()
export class Post {
@ManyToMany((type) => Category)
categories: Category[]
@RelationId((post: Post) => post.categories)
categoryIds: number[]
}Relation id is used only for representation. The underlying relation is not added/removed/changed when chaining the value.
Subscriber and listener decorators
@AfterLoad
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:
@Entity()
export class Post {
@AfterLoad()
updateCounters() {
if (this.likesCount === undefined) this.likesCount = 0
}
}Learn more about listeners.
@BeforeInsert
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:
@Entity()
export class Post {
@BeforeInsert()
updateDates() {
this.createdDate = new Date()
}
}Learn more about listeners.
@AfterInsert
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:
@Entity()
export class Post {
@AfterInsert()
resetCounters() {
this.counters = 0
}
}Learn more about listeners.
@BeforeUpdate
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:
@Entity()
export class Post {
@BeforeUpdate()
updateDates() {
this.updatedDate = new Date()
}
}Learn more about listeners.
@AfterUpdate
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:
@Entity()
export class Post {
@AfterUpdate()
updateCounters() {
this.counter = 0
}
}Learn more about listeners.
@BeforeRemove
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:
@Entity()
export class Post {
@BeforeRemove()
updateStatus() {
this.status = "removed"
}
}Learn more about listeners.
@AfterRemove
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:
@Entity()
export class Post {
@AfterRemove()
updateStatus() {
this.status = "removed"
}
}Learn more about listeners.
@BeforeSoftRemove
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:
@Entity()
export class Post {
@BeforeSoftRemove()
updateStatus() {
this.status = "soft-removed"
}
}Learn more about listeners.
@AfterSoftRemove
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:
@Entity()
export class Post {
@AfterSoftRemove()
updateStatus() {
this.status = "soft-removed"
}
}Learn more about listeners.
@BeforeRecover
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:
@Entity()
export class Post {
@BeforeRecover()
updateStatus() {
this.status = "recovered"
}
}Learn more about listeners.
@AfterRecover
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:
@Entity()
export class Post {
@AfterRecover()
updateStatus() {
this.status = "recovered"
}
}Learn more about listeners.
@EventSubscriber
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:
@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)
}
}You can implement any method from EntitySubscriberInterface. To listen to any entity, you just omit the listenTo method and use any:
@EventSubscriber()
export class PostSubscriber implements EntitySubscriberInterface {
/**
* Called before entity insertion.
*/
beforeInsert(event: InsertEvent<any>) {
console.log(`BEFORE ENTITY INSERTED: `, event.entity)
}
}Learn more about subscribers.
Other decorators
@Index
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:
@Entity()
export class User {
@Index()
@Column()
firstName: string
@Index({ unique: true })
@Column()
lastName: string
}@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
}Learn more about indexes.
@Unique
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.
Examples:
@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
}Note: MySQL stores unique constraints as unique indexes
@Check
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.
Examples:
@Entity()
@Check(`"firstName" <> 'John' AND "lastName" <> 'Doe'`)
@Check(`"age" > 18`)
export class User {
@Column()
firstName: string
@Column()
lastName: string
@Column()
age: number
}Note: MySQL does not support check constraints.
@Exclusion
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.
Examples:
@Entity()
@Exclusion(`USING gist ("room" WITH =, tsrange("from", "to") WITH &&)`)
export class RoomBooking {
@Column()
room: string
@Column()
from: Date
@Column()
to: Date
}Note: Only PostgreSQL supports exclusion constraints.
@ForeignKey
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.
Note: Do not use this decorator with relations. Foreign keys are created automatically for relations which you define using Relation decorators (
@ManyToOne,@OneToOne, etc). The@ForeignKeydecorator should only be used to create foreign keys in the database when you don't want to define an equivalent entity relationship.
Examples:
@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
}@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
}@Entity("countries")
export class Country {
@PrimaryColumn({ length: 2 })
code: string
@Column()
name: string
}@Entity("users")
export class User {
@PrimaryColumn({ name: "ref" })
id: number
@Column("uuid", { unique: true })
uuid: string
}