关系常见问题
如何创建自引用关系?
自引用关系是指指向自身的关系。当你把实体存储成树形结构时,这很有用。另外,"邻接表"模式就是用自引用关系实现的。例如,你想在应用中创建分类树。分类可以嵌套分类,被嵌套的分类又可以嵌套其他分类,依此类推。自引用关系在这里就派上用场了。本质上,自引用关系就是目标指向实体自身的普通关系。示例:
import {
Entity,
PrimaryGeneratedColumn,
Column,
ManyToOne,
OneToMany,
} from "typeorm"
@Entity()
export class Category {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@Column()
text: string
@ManyToOne((type) => Category, (category) => category.childCategories)
parentCategory: Category
@OneToMany((type) => Category, (category) => category.parentCategory)
childCategories: Category[]
}如何在不连接关系的情况下使用关系 id?
有时你希望对象中带有关联对象的 id,但不想加载它。例如:
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
@Entity()
export class Profile {
@PrimaryGeneratedColumn()
id: number
@Column()
gender: string
@Column()
photo: string
}import {
Entity,
PrimaryGeneratedColumn,
Column,
OneToOne,
JoinColumn,
} from "typeorm"
import { Profile } from "./Profile"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@OneToOne((type) => Profile)
@JoinColumn()
profile: Profile
}当你在不连接 profile 的情况下加载用户时,user 对象中不会有任何关于 profile 的信息,连 profile id 也没有:
User {
id: 1,
name: "Umed"
}但有时你想知道这个用户的 "profile id" 是什么,而不想加载整个 profile。要做到这一点,你只需要给实体再加一个用 @Column 修饰、名字与该关系所创建的列完全相同的属性。示例:
import {
Entity,
PrimaryGeneratedColumn,
Column,
OneToOne,
JoinColumn,
} from "typeorm"
import { Profile } from "./Profile"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@Column({ nullable: true })
profileId: number
@OneToOne((type) => Profile)
@JoinColumn()
profile: Profile
}就这样。下次你加载 user 对象时,它就会包含 profile id:
User {
id: 1,
name: "Umed",
profileId: 1
}如何加载实体中的关系?
加载实体关系最简单的方式是使用 FindOptions 中的 relations 选项:
const users = await dataSource.getRepository(User).find({
relations: {
profile: true,
photos: true,
videos: true,
},
})另一种更灵活的方式是使用 QueryBuilder:
const user = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.leftJoinAndSelect("user.profile", "profile")
.leftJoinAndSelect("user.photos", "photo")
.leftJoinAndSelect("user.videos", "video")
.getMany()使用 QueryBuilder 时你可以用 innerJoinAndSelect 代替 leftJoinAndSelect(要了解 LEFT JOIN 与 INNER JOIN 的区别,请查阅你的 SQL 文档),你可以按条件连接关系数据、进行排序等。
进一步了解 QueryBuilder。
避免给关系属性赋初始值
有时给关系属性赋初始值是有用的,例如:
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)
@JoinTable()
categories: Category[] = [] // 注意这里的 = [] 初始化
}然而,在 TypeORM 实体中这可能会引发问题。要理解这个问题,我们先试着加载一个 没有 设置初始值的 Question 实体。加载问题时返回的对象是这样的:
Question {
id: 1,
title: "Question about ..."
}此时当你保存这个对象,其中的 categories 不会被触碰——因为它未被设置。
但如果你有初始值,加载出来的对象会是这样:
Question {
id: 1,
title: "Question about ...",
categories: []
}当你保存该对象时,它会检查数据库中是否有任何分类绑定到这个问题——然后会把它们全部解除绑定。为什么?因为关系等于 []、或其中缺少某些项,都会被视为"有东西被移除了",没有别的办法判断某个对象是否从实体中被移除。
因此,保存这样的对象会给你带来麻烦——它会删掉之前设置的所有分类。
如何避免这种行为?很简单,不要在实体中初始化数组。同样的规则也适用于构造函数——也不要在构造函数中初始化它。
避免创建外键约束
有时出于性能原因,你可能希望实体之间有关系,但不想要外键约束。你可以用 createForeignKeyConstraints 选项(默认:true)来定义是否应创建外键约束。
import { Entity, PrimaryColumn, Column, ManyToOne } from "typeorm"
import { Person } from "./Person"
@Entity()
export class ActionLog {
@PrimaryColumn()
id: number
@Column()
date: Date
@Column()
action: string
@ManyToOne((type) => Person, {
createForeignKeyConstraints: false,
})
person: Person
}避免循环导入错误
下面是一个示例:如果你想定义实体,又不希望它们在某些环境下引发错误。在这个场景中,Action.ts 和 Person.ts 因为多对多关系而互相导入。我们使用 import type,这样就能使用类型信息而不会生成任何 JavaScript 代码。
import { Entity, PrimaryColumn, Column, ManyToMany } from "typeorm"
import type { Person } from "./Person"
@Entity()
export class ActionLog {
@PrimaryColumn()
id: number
@Column()
date: Date
@Column()
action: string
@ManyToMany("Person", (person: Person) => person.id)
person: Person
}import { Entity, PrimaryColumn, ManyToMany } from "typeorm"
import type { ActionLog } from "./Action"
@Entity()
export class Person {
@PrimaryColumn()
id: number
@ManyToMany("ActionLog", (actionLog: ActionLog) => actionLog.id)
log: ActionLog
}How to create self referencing relation?
Self-referencing relations are relations which have a relation to themselves. This is useful when you are storing entities in a tree-like structures. Also, "adjacency list" pattern is implemented using self-referenced relations. For example, you want to create categories tree in your application. Categories can nest categories, nested categories can nest other categories, etc. Self-referencing relations come handy here. Basically self-referencing relations are just regular relations that targets entity itself. Example:
import {
Entity,
PrimaryGeneratedColumn,
Column,
ManyToOne,
OneToMany,
} from "typeorm"
@Entity()
export class Category {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@Column()
text: string
@ManyToOne((type) => Category, (category) => category.childCategories)
parentCategory: Category
@OneToMany((type) => Category, (category) => category.parentCategory)
childCategories: Category[]
}How to use relation id without joining relation?
Sometimes you want to have, in your object, the id of the related object without loading it. For example:
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
@Entity()
export class Profile {
@PrimaryGeneratedColumn()
id: number
@Column()
gender: string
@Column()
photo: string
}import {
Entity,
PrimaryGeneratedColumn,
Column,
OneToOne,
JoinColumn,
} from "typeorm"
import { Profile } from "./Profile"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@OneToOne((type) => Profile)
@JoinColumn()
profile: Profile
}When you load a user without profile joined you won't have any information about profile in your user object, even profile id:
User {
id: 1,
name: "Umed"
}But sometimes you want to know what is the "profile id" of this user without loading the whole profile for this user. To do this you just need to add another property to your entity with @Column named exactly as the column created by your relation. Example:
import {
Entity,
PrimaryGeneratedColumn,
Column,
OneToOne,
JoinColumn,
} from "typeorm"
import { Profile } from "./Profile"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@Column({ nullable: true })
profileId: number
@OneToOne((type) => Profile)
@JoinColumn()
profile: Profile
}That's all. Next time you load a user object it will contain a profile id:
User {
id: 1,
name: "Umed",
profileId: 1
}How to load relations in entities?
The easiest way to load your entity relations is to use relations option in FindOptions:
const users = await dataSource.getRepository(User).find({
relations: {
profile: true,
photos: true,
videos: true,
},
})Alternative and more flexible way is to use QueryBuilder:
const user = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.leftJoinAndSelect("user.profile", "profile")
.leftJoinAndSelect("user.photos", "photo")
.leftJoinAndSelect("user.videos", "video")
.getMany()Using QueryBuilder you can do innerJoinAndSelect instead of leftJoinAndSelect (to learn the difference between LEFT JOIN and INNER JOIN refer to your SQL documentation), you can join relation data by a condition, make ordering, etc.
Learn more about QueryBuilder.
Avoid relation property initializers
Sometimes it is useful to initialize your relation properties, for 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, (category) => category.questions)
@JoinTable()
categories: Category[] = [] // see = [] initialization here
}However, in TypeORM entities it may cause problems. To understand the problem, let's first try to load a Question entity WITHOUT the initializer set. When you load a question it will return an object like this:
Question {
id: 1,
title: "Question about ..."
}Now when you save this object categories inside it won't be touched - because it is unset.
But if you have an initializer, the loaded object will look as follows:
Question {
id: 1,
title: "Question about ...",
categories: []
}When you save the object it will check if there are any categories in the database bind to the question - and it will detach all of them. Why? Because relation equal to [] or any items inside it will be considered like something was removed from it, there is no other way to check if an object was removed from entity or not.
Therefore, saving an object like this will bring you problems - it will remove all previously set categories.
How to avoid this behaviour? Simply don't initialize arrays in your entities. Same rule applies to a constructor - don't initialize it in a constructor as well.
Avoid foreign key constraint creation
Sometimes for performance reasons you might want to have a relation between entities, but without foreign key constraint. You can define if foreign key constraint should be created with createForeignKeyConstraints option (default: true).
import { Entity, PrimaryColumn, Column, ManyToOne } from "typeorm"
import { Person } from "./Person"
@Entity()
export class ActionLog {
@PrimaryColumn()
id: number
@Column()
date: Date
@Column()
action: string
@ManyToOne((type) => Person, {
createForeignKeyConstraints: false,
})
person: Person
}Avoid circular import errors
Here is an example if you want to define your entities, and you don't want those to cause errors in some environments. In this situation we have Action.ts and Person.ts importing each other for a many-to-many relationship. We use import type so that we can use the type information without any JavaScript code being generated.
import { Entity, PrimaryColumn, Column, ManyToMany } from "typeorm"
import type { Person } from "./Person"
@Entity()
export class ActionLog {
@PrimaryColumn()
id: number
@Column()
date: Date
@Column()
action: string
@ManyToMany("Person", (person: Person) => person.id)
person: Person
}import { Entity, PrimaryColumn, ManyToMany } from "typeorm"
import type { ActionLog } from "./Action"
@Entity()
export class Person {
@PrimaryColumn()
id: number
@ManyToMany("ActionLog", (actionLog: ActionLog) => actionLog.id)
log: ActionLog
}