# 一对一关系

> 英文标题：One-to-one relations
> 官网原文：https://typeorm.io/docs/relations/one-to-one-relations
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 23 块

---

<!-- EN -->
# One-to-one relations

<!-- ZH -->
# 一对一关系

<!-- EN -->
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.

<!-- ZH -->
一对一是一种 A 只包含一个 B 实例、且 B 只包含一个 A 实例的关系。以 `User` 和 `Profile` 实体为例。一个用户只能有一个档案，而一个档案只属于一个用户。

<!-- EN -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity()
export class Profile {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    gender: string

    @Column()
    photo: string
}
```

<!-- ZH -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity()
export class Profile {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    gender: string

    @Column()
    photo: string
}
```

<!-- EN -->
```typescript
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
}
```

<!-- ZH -->
```typescript
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
}
```

<!-- EN -->
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.

<!-- ZH -->
这里我们给 `user` 加上了 `@OneToOne`，并把目标关系类型指定为 `Profile`。我们还加上了 `@JoinColumn`，它是必需的，并且只能设置在关系的一侧。你把 `@JoinColumn` 设在哪一侧，那一侧的表就会持有"关系 id"以及指向目标实体表的外键。

<!-- EN -->
This example will produce the following tables:

<!-- ZH -->
这个示例会生成以下表：

<!-- EN -->
```text
+-------------+--------------+----------------------------+
|                        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                |
+-------------+--------------+----------------------------+
```

<!-- ZH -->
```text
+-------------+--------------+----------------------------+
|                        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                |
+-------------+--------------+----------------------------+
```

<!-- EN -->
Again, `@JoinColumn` must be set only on one side of the relation - the side that must have the foreign key in the database table.

<!-- ZH -->
再次强调，`@JoinColumn` 只能设置在关系的一侧——也就是数据库表中必须持有外键的那一侧。

<!-- EN -->
Example how to save such a relation:

<!-- ZH -->
保存这种关系的示例：

<!-- EN -->
```typescript
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)
```

<!-- ZH -->
```typescript
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)
```

<!-- EN -->
With [cascades](https://typeorm.io/docs/relations/relations#cascades) enabled you can save this relation with only one `save` call.

<!-- ZH -->
启用[级联](https://typeorm.io/docs/relations/relations#cascades)后，你只需一次 `save` 调用就能保存这个关系。

<!-- EN -->
To load user with profile inside you must specify relation in `FindOptions`:

<!-- ZH -->
要加载带有档案的用户，你必须在 `FindOptions` 中指定关系：

<!-- EN -->
```typescript
const users = await dataSource.getRepository(User).find({
    relations: {
        profile: true,
    },
})
```

<!-- ZH -->
```typescript
const users = await dataSource.getRepository(User).find({
    relations: {
        profile: true,
    },
})
```

<!-- EN -->
Or using `QueryBuilder` you can join them:

<!-- ZH -->
或者使用 `QueryBuilder` 把它们连接起来：

<!-- EN -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .leftJoinAndSelect("user.profile", "profile")
    .getMany()
```

<!-- ZH -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .leftJoinAndSelect("user.profile", "profile")
    .getMany()
```

<!-- EN -->
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.

<!-- ZH -->
在关系上启用急加载后，你不必在 find 命令中指定关系，因为它 **总是** 会被自动加载。如果使用 QueryBuilder，急加载关系会被禁用，你必须用 `leftJoinAndSelect` 来加载该关系。

<!-- EN -->
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.

<!-- ZH -->
关系可以是单向的，也可以是双向的。单向关系只在其中一侧有关系装饰器。双向关系在关系的两侧都有装饰器。

<!-- EN -->
We just created a uni-directional relation. Let's make it bi-directional:

<!-- ZH -->
我们刚才创建的是单向关系。把它改成双向的：

<!-- EN -->
```typescript
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
}
```

<!-- ZH -->
```typescript
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
}
```

<!-- EN -->
```typescript
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
}
```

<!-- ZH -->
```typescript
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
}
```

<!-- EN -->
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.

<!-- ZH -->
我们刚刚把关系改成了双向。注意，反向关系没有 `@JoinColumn`。`@JoinColumn` 只能出现在关系的一侧——也就是将持有外键的那张表上。

<!-- EN -->
Bi-directional relations allow you to join relations from both sides using `QueryBuilder`:

<!-- ZH -->
双向关系让你可以用 `QueryBuilder` 从两侧连接关系：

<!-- EN -->
```typescript
const profiles = await dataSource
    .getRepository(Profile)
    .createQueryBuilder("profile")
    .leftJoinAndSelect("profile.user", "user")
    .getMany()
```

<!-- ZH -->
```typescript
const profiles = await dataSource
    .getRepository(Profile)
    .createQueryBuilder("profile")
    .leftJoinAndSelect("profile.user", "user")
    .getMany()
```
