一对一关系
一对一是一种 A 只包含一个 B 实例、且 B 只包含一个 A 实例的关系。以 User 和 Profile 实体为例。一个用户只能有一个档案,而一个档案只属于一个用户。
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(() => Profile)
@JoinColumn()
profile: Profile
}这里我们给 user 加上了 @OneToOne,并把目标关系类型指定为 Profile。我们还加上了 @JoinColumn,它是必需的,并且只能设置在关系的一侧。你把 @JoinColumn 设在哪一侧,那一侧的表就会持有"关系 id"以及指向目标实体表的外键。
这个示例会生成以下表:
+-------------+--------------+----------------------------+
| profile |
+-------------+--------------+----------------------------+
| id | int | PRIMARY KEY AUTO_INCREMENT |
| gender | varchar(255) | |
| photo | varchar(255) | |
+-------------+--------------+----------------------------+
+-------------+--------------+----------------------------+
| user |
+-------------+--------------+----------------------------+
| id | int | PRIMARY KEY AUTO_INCREMENT |
| name | varchar(255) | |
| profileId | int | FOREIGN KEY |
+-------------+--------------+----------------------------+再次强调,@JoinColumn 只能设置在关系的一侧——也就是数据库表中必须持有外键的那一侧。
保存这种关系的示例:
const profile = new Profile()
profile.gender = "male"
profile.photo = "me.jpg"
await dataSource.manager.save(profile)
const user = new User()
user.name = "Joe Smith"
user.profile = profile
await dataSource.manager.save(user)启用级联后,你只需一次 save 调用就能保存这个关系。
要加载带有档案的用户,你必须在 FindOptions 中指定关系:
const users = await dataSource.getRepository(User).find({
relations: {
profile: true,
},
})或者使用 QueryBuilder 把它们连接起来:
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.leftJoinAndSelect("user.profile", "profile")
.getMany()在关系上启用急加载后,你不必在 find 命令中指定关系,因为它 总是 会被自动加载。如果使用 QueryBuilder,急加载关系会被禁用,你必须用 leftJoinAndSelect 来加载该关系。
关系可以是单向的,也可以是双向的。单向关系只在其中一侧有关系装饰器。双向关系在关系的两侧都有装饰器。
我们刚才创建的是单向关系。把它改成双向的:
import { Entity, PrimaryGeneratedColumn, Column, OneToOne } from "typeorm"
import { User } from "./User"
@Entity()
export class Profile {
@PrimaryGeneratedColumn()
id: number
@Column()
gender: string
@Column()
photo: string
@OneToOne(() => User, (user) => user.profile) // 把反向方作为第二个参数指定
user: User
}import {
Entity,
PrimaryGeneratedColumn,
Column,
OneToOne,
JoinColumn,
} from "typeorm"
import { Profile } from "./Profile"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@OneToOne(() => Profile, (profile) => profile.user) // 把反向方作为第二个参数指定
@JoinColumn()
profile: Profile
}我们刚刚把关系改成了双向。注意,反向关系没有 @JoinColumn。@JoinColumn 只能出现在关系的一侧——也就是将持有外键的那张表上。
双向关系让你可以用 QueryBuilder 从两侧连接关系:
const profiles = await dataSource
.getRepository(Profile)
.createQueryBuilder("profile")
.leftJoinAndSelect("profile.user", "user")
.getMany()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.
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(() => Profile)
@JoinColumn()
profile: Profile
}Here we added @OneToOne to the user and specified the target relation type to be Profile. We also added @JoinColumn which is required and must be set only on one side of the relation. The side you set @JoinColumn on, that side's table will contain a "relation id" and foreign keys to the target entity table.
This example will produce the following tables:
+-------------+--------------+----------------------------+
| profile |
+-------------+--------------+----------------------------+
| id | int | PRIMARY KEY AUTO_INCREMENT |
| gender | varchar(255) | |
| photo | varchar(255) | |
+-------------+--------------+----------------------------+
+-------------+--------------+----------------------------+
| user |
+-------------+--------------+----------------------------+
| id | int | PRIMARY KEY AUTO_INCREMENT |
| name | varchar(255) | |
| profileId | int | FOREIGN KEY |
+-------------+--------------+----------------------------+Again, @JoinColumn must be set only on one side of the relation - the side that must have the foreign key in the database table.
Example how to save such a relation:
const profile = new Profile()
profile.gender = "male"
profile.photo = "me.jpg"
await dataSource.manager.save(profile)
const user = new User()
user.name = "Joe Smith"
user.profile = profile
await dataSource.manager.save(user)With cascades enabled you can save this relation with only one save call.
To load user with profile inside you must specify relation in FindOptions:
const users = await dataSource.getRepository(User).find({
relations: {
profile: true,
},
})Or using QueryBuilder you can join them:
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.leftJoinAndSelect("user.profile", "profile")
.getMany()With eager loading enabled on a relation, you don't have to specify relations in the find command as it will ALWAYS be loaded automatically. If you use QueryBuilder eager relations are disabled, you have to use leftJoinAndSelect to load the relation.
Relations can be uni-directional and bi-directional. Uni-directional are relations with a relation decorator only on one side. Bi-directional are relations with decorators on both sides of a relation.
We just created a uni-directional relation. Let's make it bi-directional:
import { Entity, PrimaryGeneratedColumn, Column, OneToOne } from "typeorm"
import { User } from "./User"
@Entity()
export class Profile {
@PrimaryGeneratedColumn()
id: number
@Column()
gender: string
@Column()
photo: string
@OneToOne(() => User, (user) => user.profile) // specify inverse side as a second parameter
user: User
}import {
Entity,
PrimaryGeneratedColumn,
Column,
OneToOne,
JoinColumn,
} from "typeorm"
import { Profile } from "./Profile"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@OneToOne(() => Profile, (profile) => profile.user) // specify inverse side as a second parameter
@JoinColumn()
profile: Profile
}We just made our relation bi-directional. Note, inverse relation does not have a @JoinColumn. @JoinColumn must only be on one side of the relation - on the table that will own the foreign key.
Bi-directional relations allow you to join relations from both sides using QueryBuilder:
const profiles = await dataSource
.getRepository(Profile)
.createQueryBuilder("profile")
.leftJoinAndSelect("profile.user", "user")
.getMany()