# 处理关系

> 英文标题：Working with Relations
> 官网原文：https://typeorm.io/docs/query-builder/relational-query-builder
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 20 块

---

<!-- EN -->
# Working with Relations

<!-- ZH -->
# 处理关系

<!-- EN -->
`RelationQueryBuilder` is a special type of `QueryBuilder` which allows you to work with your relations. Using it, you can bind entities to each other in the database without the need to load any entities, or you can load related entities easily.

<!-- ZH -->
`RelationQueryBuilder` 是一种特殊的 `QueryBuilder`，让你可以操作关系。借助它，你可以在数据库中把实体彼此绑定而不必加载任何实体，也可以轻松加载关联实体。

<!-- EN -->
For example, we have a `Post` entity and it has a many-to-many relation to `Category` called `categories`. Let's add a new category to this many-to-many relation:

<!-- ZH -->
例如，我们有一个 `Post` 实体，它有一个指向 `Category`、名为 `categories` 的多对多关系。给这个多对多关系添加一个新分类：

<!-- EN -->
```typescript
await dataSource
    .createQueryBuilder()
    .relation(Post, "categories")
    .of(post)
    .add(category)
```

<!-- ZH -->
```typescript
await dataSource
    .createQueryBuilder()
    .relation(Post, "categories")
    .of(post)
    .add(category)
```

<!-- EN -->
This code is equivalent to doing this:

<!-- ZH -->
这段代码等价于下面这样：

<!-- EN -->
```typescript
const postRepository = dataSource.manager.getRepository(Post)
const post = await postRepository.findOne({
    where: {
        id: 1,
    },
    relations: {
        categories: true,
    },
})
post.categories.push(category)
await postRepository.save(post)
```

<!-- ZH -->
```typescript
const postRepository = dataSource.manager.getRepository(Post)
const post = await postRepository.findOne({
    where: {
        id: 1,
    },
    relations: {
        categories: true,
    },
})
post.categories.push(category)
await postRepository.save(post)
```

<!-- EN -->
But more efficient, because it does a minimal number of operations, and binds entities in the database, unlike calling a bulky `save` method call.

<!-- ZH -->
但它更高效，因为它执行的操作数量最少，并且是在数据库中绑定实体，而不是调用笨重的 `save` 方法。

<!-- EN -->
Also, another benefit of such an approach is that you don't need to load every related entity before pushing into it. For example, if you have ten thousand categories inside a single post, adding new posts to this list may become problematic for you, because the standard way of doing this is to load the post with all ten thousand categories, push a new category, and save it. This results in very heavy performance costs and is basically inapplicable in production results. However, using `RelationQueryBuilder` solves this problem.

<!-- ZH -->
此外，这种方式的另一个好处是，你不需要在推入之前加载每一个关联实体。例如，如果一篇帖子里有一万个分类，往这个列表里添加新内容可能会变得很麻烦，因为标准做法是把这篇帖子连同它的一万个分类全部加载出来，推入一个新分类，再保存。这会带来非常高的性能开销，在生产环境中基本不可行。而使用 `RelationQueryBuilder` 就能解决这个问题。

<!-- EN -->
Also, there is no real need to use entities when you "bind" things, since you can use entity ids instead. For example, let's add a category with id = 3 into post with id = 1:

<!-- ZH -->
另外，在"绑定"时并不真的需要使用实体，因为你可以改用实体 id。例如，把 id = 3 的分类加到 id = 1 的帖子中：

<!-- EN -->
```typescript
await dataSource.createQueryBuilder().relation(Post, "categories").of(1).add(3)
```

<!-- ZH -->
```typescript
await dataSource.createQueryBuilder().relation(Post, "categories").of(1).add(3)
```

<!-- EN -->
If you are using composite primary keys, you have to pass them as an id map, for example:

<!-- ZH -->
如果你使用复合主键，就必须以 id 映射的形式传入，例如：

<!-- EN -->
```typescript
await dataSource
    .createQueryBuilder()
    .relation(Post, "categories")
    .of({ firstPostId: 1, secondPostId: 3 })
    .add({ firstCategoryId: 2, secondCategoryId: 4 })
```

<!-- ZH -->
```typescript
await dataSource
    .createQueryBuilder()
    .relation(Post, "categories")
    .of({ firstPostId: 1, secondPostId: 3 })
    .add({ firstCategoryId: 2, secondCategoryId: 4 })
```

<!-- EN -->
You can remove entities the same way you add them:

<!-- ZH -->
移除实体的方式与添加相同：

<!-- EN -->
```typescript
// this code removes a category from a given post
await dataSource
    .createQueryBuilder()
    .relation(Post, "categories")
    .of(post) // you can use just post id as well
    .remove(category) // you can use just category id as well
```

<!-- ZH -->
```typescript
// 这段代码从给定帖子中移除一个分类
await dataSource
    .createQueryBuilder()
    .relation(Post, "categories")
    .of(post) // 你也可以只传 post id
    .remove(category) // 你也可以只传 category id
```

<!-- EN -->
Adding and removing related entities works in `many-to-many` and `one-to-many` relations. For `one-to-one` and `many-to-one` relations use `set` instead:

<!-- ZH -->
添加和移除关联实体适用于 `many-to-many` 和 `one-to-many` 关系。对 `one-to-one` 和 `many-to-one` 关系，请改用 `set`：

<!-- EN -->
```typescript
// this code sets category of a given post
await dataSource
    .createQueryBuilder()
    .relation(Post, "categories")
    .of(post) // you can use just post id as well
    .set(category) // you can use just category id as well
```

<!-- ZH -->
```typescript
// 这段代码设置给定帖子的分类
await dataSource
    .createQueryBuilder()
    .relation(Post, "categories")
    .of(post) // 你也可以只传 post id
    .set(category) // 你也可以只传 category id
```

<!-- EN -->
If you want to unset a relation (set it to null), simply pass `null` to a `set` method:

<!-- ZH -->
如果你想解除一个关系（把它设为 null），只需给 `set` 方法传入 `null`：

<!-- EN -->
```typescript
// this code unsets category of a given post
await dataSource
    .createQueryBuilder()
    .relation(Post, "categories")
    .of(post) // you can use just post id as well
    .set(null)
```

<!-- ZH -->
```typescript
// 这段代码解除给定帖子的分类
await dataSource
    .createQueryBuilder()
    .relation(Post, "categories")
    .of(post) // 你也可以只传 post id
    .set(null)
```

<!-- EN -->
Besides updating relations, the relational query builder also allows you to load relational entities. For example, lets say inside a `Post` entity we have a many-to-many `categories` relation and a many-to-one `user` relation, to load those relations you can use following code:

<!-- ZH -->
除了更新关系，关系型 query builder 还允许你加载关系实体。例如，假设在 `Post` 实体中我们有一个多对多的 `categories` 关系和一个多对一的 `user` 关系，要加载这些关系你可以使用下面的代码：

<!-- EN -->
```typescript
const post = await dataSource.manager.findOneBy(Post, {
    id: 1,
})

post.categories = await dataSource
    .createQueryBuilder()
    .relation(Post, "categories")
    .of(post) // you can use just post id as well
    .loadMany()

post.author = await dataSource
    .createQueryBuilder()
    .relation(Post, "user")
    .of(post) // you can use just post id as well
    .loadOne()
```

<!-- ZH -->
```typescript
const post = await dataSource.manager.findOneBy(Post, {
    id: 1,
})

post.categories = await dataSource
    .createQueryBuilder()
    .relation(Post, "categories")
    .of(post) // 你也可以只传 post id
    .loadMany()

post.author = await dataSource
    .createQueryBuilder()
    .relation(Post, "user")
    .of(post) // 你也可以只传 post id
    .loadOne()
```
