关系
什么是关系?
关系能让你轻松地处理相关联的实体。关系有几种类型:
关系选项
你可以为关系指定若干选项:
eager: boolean(默认:false)- 设为 true 时,在该实体上使用find*方法或QueryBuilder时,这个关系总会随主实体一起加载cascade: boolean | ("insert" | "update")[](默认:false)- 设为 true 时,关联对象会在数据库中被插入和更新。你也可以指定一个级联选项数组。onDelete: "RESTRICT"|"CASCADE"|"SET NULL"(默认:RESTRICT)- 指定被引用对象被删除时外键应如何表现deferrable: "INITIALLY DEFERRED"|"INITIALLY IMMEDIATE"- 设置后,外键约束变为可延迟的(例如在提交时校验)。对多对多关系,它同时作用于中间表的两个外键。在 PostgreSQL、better-sqlite3 和 SAP HANA 上受支持。nullable: boolean(默认:true)- 表示该关系的列是否可空。默认是可空的。对ManyToOne和拥有方OneToOne关系,设置nullable: false还会让 TypeORM 在加载该关系时使用INNER JOIN而不是LEFT JOIN,因为关联实体必然存在。orphanedRowAction: "nullify" | "delete" | "soft-delete" | "disable"(默认:nullify)- 当保存父对象(已启用级联)时,数据库中仍然存在的某个子对象 / 某些子对象不在其中,该选项控制如何处理它们。- nullify 会移除关系键。如果外键列不可空,孤儿行会被删除,因为它无法被设为
null。 - delete 会从数据库中删除这些子对象。
- soft-delete 会把子对象标记为软删除。
- disable 会保持关系不变。要删除的话,必须使用它们自己的 repository。
- nullify 会移除关系键。如果外键列不可空,孤儿行会被删除,因为它无法被设为
级联
级联示例:
import { Entity, PrimaryGeneratedColumn, Column, ManyToMany } from "typeorm"
import { Question } from "./Question"
@Entity()
export class Category {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@ManyToMany((type) => Question, (question) => question.categories)
questions: Question[]
}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, (category) => category.questions, {
cascade: true,
})
@JoinTable()
categories: Category[]
}const category1 = new Category()
category1.name = "ORMs"
const category2 = new Category()
category2.name = "Programming"
const question = new Question()
question.title = "How to ask questions?"
question.text = "Where can I ask TypeORM-related questions?"
question.categories = [category1, category2]
await dataSource.manager.save(question)如你所见,在这个示例中我们并没有为 category1 和 category2 调用 save。它们会被自动插入,因为我们把 cascade 设成了 true。
请记住——能力越大,责任越大。级联看起来是处理关系的一种又好又简单的方式,但当某个不该被保存的对象被存进数据库时,它也可能带来 bug 和安全问题。此外,它让"把新对象保存进数据库"这件事变得不那么显式。
级联选项
cascade 选项可以设为 boolean,也可以设为级联选项数组 ("insert" | "update" | "remove" | "soft-remove" | "recover")[]。
它默认为 false,即不启用任何级联。设置 cascade: true 会启用完整级联。你也可以通过提供数组来指定具体选项。
例如:
@Entity(Post)
export class Post {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@Column()
text: string
// 对 categories 启用完整级联。
@ManyToMany((type) => PostCategory, {
cascade: true,
})
@JoinTable()
categories: PostCategory[]
// 这里的级联插入意味着,如果该关系上设置了新的 PostDetails 实例,
// 保存这个 Post 实体时它会被自动插入数据库
@ManyToMany((type) => PostDetails, (details) => details.posts, {
cascade: ["insert"],
})
@JoinTable()
details: PostDetails[]
// 这里的级联更新意味着,如果已有的 PostImage 发生了变化,
// 保存这个 Post 实体时它会被自动更新到数据库
@ManyToMany((type) => PostImage, (image) => image.posts, {
cascade: ["update"],
})
@JoinTable()
images: PostImage[]
// 这里的级联插入与更新意味着,如果出现了新的 PostInformation 实例
// 或已有的实例被更新,它们会在保存这个 Post 实体时被自动插入或更新
@ManyToMany((type) => PostInformation, (information) => information.posts, {
cascade: ["insert", "update"],
})
@JoinTable()
informations: PostInformation[]
}级联删除
使用 cascade: ["remove"] 或 cascade: true 时,调用 manager.remove(entity) 也会删除该实体实例上已加载的关联实体。TypeORM 只会遍历对象上已填充的关系——如果某个关系没有被加载,它的子对象不会被级联删除。请确保在删除前先加载关系:
const post = await manager.findOne(Post, {
where: { id: 1 },
relations: { categories: true },
})
await manager.remove(post) // categories 也会被删除@JoinColumn 选项
@JoinColumn 不仅定义了关系的哪一侧持有带外键的连接列,还允许你自定义连接列名和被引用列名。
当我们设置 @JoinColumn 时,它会自动在数据库中创建一个名为 propertyName + referencedColumnName 的列。例如:
@ManyToOne(type => Category)
@JoinColumn() // 这个装饰器对 @ManyToOne 是可选的,但对 @OneToOne 是必需的
category: Category;这段代码会在数据库中创建一个 categoryId 列。如果你想改变它在数据库中的名字,可以指定自定义的连接列名:
@ManyToOne(type => Category)
@JoinColumn({ name: "cat_id" })
category: Category;连接列总是对其他某些列的引用(通过外键)。默认情况下,你的关系总是引用关联实体的主键列。如果你想与关联实体的其他列建立关系,也可以在 @JoinColumn 中指定它们:
@ManyToOne(type => Category)
@JoinColumn({ referencedColumnName: "name" })
category: Category;此时该关系引用的是 Category 实体的 name,而不是 id。该关系的列名会变成 categoryName。
你也可以连接多个列。注意它们默认并不引用关联实体的主键列:你必须提供被引用的列名。
@ManyToOne(type => Category)
@JoinColumn([
{ name: "category_id", referencedColumnName: "id" },
{ name: "locale_id", referencedColumnName: "locale_id" }
])
category: Category;注意: 使用复合
@JoinColumn或@JoinTable时,TypeORM 会自动对外键列排序,使其与被引用实体的主键顺序一致。这能保证与 MySQL、MSSQL 和 SAP HANA 这类要求外键列按索引顺序引用主键列的数据库兼容。
@JoinTable 选项
@JoinTable 用于 many-to-many 关系,描述"中间表"的连接列。中间表是 TypeORM 自动创建的一张特殊独立表,其中的列引用相关联的实体。你可以用 @JoinColumn 修改中间表中的列名及其被引用列,也可以修改生成的"中间表"的表名。
@ManyToMany(type => Category)
@JoinTable({
name: "question_categories", // 该关系中间表的表名
joinColumn: {
name: "question",
referencedColumnName: "id"
},
inverseJoinColumn: {
name: "category",
referencedColumnName: "id"
}
})
categories: Category[];如果目标表有复合主键,那么必须给 @JoinTable 传入一个属性数组。
What are relations?
Relations helps you to work with related entities easily. There are several types of relations:
- one-to-one using
@OneToOne - many-to-one using
@ManyToOne - one-to-many using
@OneToMany - many-to-many using
@ManyToMany
Relation options
There are several options you can specify for relations:
eager: boolean(default:false) - If set to true, the relation will always be loaded with the main entity when usingfind*methods orQueryBuilderon this entitycascade: boolean | ("insert" | "update")[](default:false) - If set to true, the related object will be inserted and updated in the database. You can also specify an array of cascade options.onDelete: "RESTRICT"|"CASCADE"|"SET NULL"(default:RESTRICT) - specifies how foreign key should behave when referenced object is deleteddeferrable: "INITIALLY DEFERRED"|"INITIALLY IMMEDIATE"- When set, foreign key constraints are deferrable (e.g. validated at commit time). For many-to-many relations this applies to both junction-table foreign keys. Supported on PostgreSQL, better-sqlite3, and SAP HANA.nullable: boolean(default:true) - Indicates whether this relation's column is nullable or not. By default it is nullable. ForManyToOneand owningOneToOnerelations, settingnullable: falsealso causes TypeORM to useINNER JOINinstead ofLEFT JOINwhen loading the relation, since the related entity is guaranteed to exist.orphanedRowAction: "nullify" | "delete" | "soft-delete" | "disable"(default:nullify) - When a parent is saved (cascading enabled) without a child/children that still exists in database, this will control what shall happen to them.- nullify will remove the relation key. If the foreign key column is non-nullable, the orphaned row will be deleted instead since it cannot be set to
null. - delete will remove these children from database.
- soft-delete will mark children as soft-deleted.
- disable will keep the relation intact. To delete, one has to use their own repository.
- nullify will remove the relation key. If the foreign key column is non-nullable, the orphaned row will be deleted instead since it cannot be set to
Cascades
Cascades example:
import { Entity, PrimaryGeneratedColumn, Column, ManyToMany } from "typeorm"
import { Question } from "./Question"
@Entity()
export class Category {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@ManyToMany((type) => Question, (question) => question.categories)
questions: Question[]
}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, (category) => category.questions, {
cascade: true,
})
@JoinTable()
categories: Category[]
}const category1 = new Category()
category1.name = "ORMs"
const category2 = new Category()
category2.name = "Programming"
const question = new Question()
question.title = "How to ask questions?"
question.text = "Where can I ask TypeORM-related questions?"
question.categories = [category1, category2]
await dataSource.manager.save(question)As you can see in this example we did not call save for category1 and category2. They will be automatically inserted, because we set cascade to true.
Keep in mind - great power comes with great responsibility. Cascades may seem like a good and easy way to work with relations, but they may also bring bugs and security issues when some undesired object is being saved into the database. Also, they provide a less explicit way of saving new objects into the database.
Cascade Options
The cascade option can be set as a boolean or an array of cascade options ("insert" | "update" | "remove" | "soft-remove" | "recover")[].
It will default to false, meaning no cascades. Setting cascade: true will enable full cascades. You can also specify options by providing an array.
For example:
@Entity(Post)
export class Post {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@Column()
text: string
// Full cascades on categories.
@ManyToMany((type) => PostCategory, {
cascade: true,
})
@JoinTable()
categories: PostCategory[]
// Cascade insert here means if there is a new PostDetails instance set
// on this relation, it will be inserted automatically to the db when you save this Post entity
@ManyToMany((type) => PostDetails, (details) => details.posts, {
cascade: ["insert"],
})
@JoinTable()
details: PostDetails[]
// Cascade update here means if there are changes to an existing PostImage, it
// will be updated automatically to the db when you save this Post entity
@ManyToMany((type) => PostImage, (image) => image.posts, {
cascade: ["update"],
})
@JoinTable()
images: PostImage[]
// Cascade insert & update here means if there are new PostInformation instances
// or an update to an existing one, they will be automatically inserted or updated
// when you save this Post entity
@ManyToMany((type) => PostInformation, (information) => information.posts, {
cascade: ["insert", "update"],
})
@JoinTable()
informations: PostInformation[]
}Cascade remove
When using cascade: ["remove"] or cascade: true, calling manager.remove(entity) will also remove related entities that are loaded on the entity instance. TypeORM only traverses relations that are populated on the object — if a relation is not loaded, its children will not be cascade-removed. Make sure to load relations before removing:
const post = await manager.findOne(Post, {
where: { id: 1 },
relations: { categories: true },
})
await manager.remove(post) // categories will also be removed@JoinColumn options
@JoinColumn not only defines which side of the relation contains the join column with a foreign key, but also allows you to customize join column name and referenced column name.
When we set @JoinColumn, it automatically creates a column in the database named propertyName + referencedColumnName. For example:
@ManyToOne(type => Category)
@JoinColumn() // this decorator is optional for @ManyToOne, but required for @OneToOne
category: Category;This code will create a categoryId column in the database. If you want to change this name in the database you can specify a custom join column name:
@ManyToOne(type => Category)
@JoinColumn({ name: "cat_id" })
category: Category;Join columns are always a reference to some other columns (using a foreign key). By default your relation always refers to the primary column of the related entity. If you want to create relation with other columns of the related entity - you can specify them in @JoinColumn as well:
@ManyToOne(type => Category)
@JoinColumn({ referencedColumnName: "name" })
category: Category;The relation now refers to name of the Category entity, instead of id. Column name for that relation will become categoryName.
You can also join multiple columns. Note that they do not reference the primary column of the related entity by default: you must provide the referenced column name.
@ManyToOne(type => Category)
@JoinColumn([
{ name: "category_id", referencedColumnName: "id" },
{ name: "locale_id", referencedColumnName: "locale_id" }
])
category: Category;Note: When using composite
@JoinColumnor@JoinTable, TypeORM automatically sorts the foreign key columns to match the referenced entity's primary key order. This ensures compatibility with databases like MySQL, MSSQL, and SAP HANA that require FK columns to reference PK columns in index order.
@JoinTable options
@JoinTable is used for many-to-many relations and describes join columns of the "junction" table. A junction table is a special separate table created automatically by TypeORM with columns that refer to the related entities. You can change column names inside junction tables and their referenced columns with @JoinColumn: You can also change the name of the generated "junction" table.
@ManyToMany(type => Category)
@JoinTable({
name: "question_categories", // table name for the junction table of this relation
joinColumn: {
name: "question",
referencedColumnName: "id"
},
inverseJoinColumn: {
name: "category",
referencedColumnName: "id"
}
})
categories: Category[];If the destination table has composite primary keys, then an array of properties must be sent to @JoinTable.