Many-to-many relations

What are many-to-many relations

Many-to-many is a relation where A contains multiple instances of B, and B contain multiple instances of A. Let's take for example Question and Category entities. A question can have multiple categories, and each category can have multiple questions.
1
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";
2
​
3
@Entity()
4
export class Category {
5
@PrimaryGeneratedColumn()
6
id: number;
7
​
8
@Column()
9
name: string;
10
}
Copied!
1
import { Entity, PrimaryGeneratedColumn, Column, ManyToMany, JoinTable } from "typeorm";
2
import { Category } from "./Category";
3
​
4
@Entity()
5
export class Question {
6
@PrimaryGeneratedColumn()
7
id: number;
8
​
9
@Column()
10
title: string;
11
​
12
@Column()
13
text: string;
14
​
15
@ManyToMany(() => Category)
16
@JoinTable()
17
categories: Category[];
18
}
Copied!
@JoinTable() is required for @ManyToMany relations. You must put @JoinTable on one (owning) side of relation.
This example will produce following tables:
1
+-------------+--------------+----------------------------+
2
| category |
3
+-------------+--------------+----------------------------+
4
| id | int(11) | PRIMARY KEY AUTO_INCREMENT |
5
| name | varchar(255) | |
6
+-------------+--------------+----------------------------+
7
​
8
+-------------+--------------+----------------------------+
9
| question |
10
+-------------+--------------+----------------------------+
11
| id | int(11) | PRIMARY KEY AUTO_INCREMENT |
12
| title | varchar(255) | |
13
| text | varchar(255) | |
14
+-------------+--------------+----------------------------+
15
​
16
+-------------+--------------+----------------------------+
17
| question_categories_category |
18
+-------------+--------------+----------------------------+
19
| questionId | int(11) | PRIMARY KEY FOREIGN KEY |
20
| categoryId | int(11) | PRIMARY KEY FOREIGN KEY |
21
+-------------+--------------+----------------------------+
Copied!

Saving many-to-many relations

With cascades enabled, you can save this relation with only one save call.
1
const category1 = new Category();
2
category1.name = "animals";
3
await connection.manager.save(category1);
4
​
5
const category2 = new Category();
6
category2.name = "zoo";
7
await connection.manager.save(category2);
8
​
9
const question = new Question();
10
question.title = "dogs";
11
question.text = "who let the dogs out?";
12
question.categories = [category1, category2];
13
await connection.manager.save(question);
Copied!

Deleting many-to-many relations

With cascades enabled, you can delete this relation with only one save call.
To delete a many-to-many relationship between two records, remove it from the corresponding field and save the record.
1
const question = getRepository(Question);
2
question.categories = question.categories.filter(category => {
3
return category.id !== categoryToRemove.id
4
})
5
await connection.manager.save(question)
Copied!
This will only remove the record in the join table. The question and categoryToRemove records will still exist.

Soft Deleting a relationship with cascade

This example shows how the cascading soft delete behaves:
1
const category1 = new Category();
2
category1.name = "animals";
3
​
4
const category2 = new Category();
5
category2.name = "zoo";
6
​
7
const question = new Question();
8
question.categories = [category1, category2];
9
const newQuestion = await connection.manager.save(question);
10
​
11
await connection.manager.softRemove(newQuestion);
Copied!
In this example we did not call save or softRemove for category1 and category2, but they will be automatically saved and soft-deleted when the cascade of relation options is set to true like this:
1
import { Entity, PrimaryGeneratedColumn, Column, ManyToMany, JoinTable } from "typeorm";
2
import { Category } from "./Category";
3
​
4
@Entity()
5
export class Question {
6
@PrimaryGeneratedColumn()
7
id: number;
8
​
9
@ManyToMany(() => Category, category => category.questions, {
10
cascade: true
11
})
12
@JoinTable()
13
categories: Category[];
14
}
Copied!

Loading many-to-many relations

To load questions with categories inside you must specify the relation in FindOptions:
1
const questionRepository = connection.getRepository(Question);
2
const questions = await questionRepository.find({ relations: ["categories"] });
Copied!
Or using QueryBuilder you can join them:
1
const questions = await connection
2
.getRepository(Question)
3
.createQueryBuilder("question")
4
.leftJoinAndSelect("question.categories", "category")
5
.getMany();
Copied!
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.

Bi-directional relations

Relations can be uni-directional and bi-directional. Uni-directional relations are relations with a relation decorator only on one side. Bi-directional relations are relations with decorators on both sides of a relation.
We just created a uni-directional relation. Let's make it bi-directional:
1
import { Entity, PrimaryGeneratedColumn, Column, ManyToMany } from "typeorm";
2
import { Question } from "./Question";
3
​
4
@Entity()
5
export class Category {
6
@PrimaryGeneratedColumn()
7
id: number;
8
​
9
@Column()
10
name: string;
11
​
12
@ManyToMany(() => Question, question => question.categories)
13
questions: Question[];
14
}
Copied!
1
import { Entity, PrimaryGeneratedColumn, Column, ManyToMany, JoinTable } from "typeorm";
2
import { Category } from "./Category";
3
​
4
@Entity()
5
export class Question {
6
@PrimaryGeneratedColumn()
7
id: number;
8
​
9
@Column()
10
title: string;
11
​
12
@Column()
13
text: string;
14
​
15
@ManyToMany(() => Category, category => category.questions)
16
@JoinTable()
17
categories: Category[];
18
}
Copied!
We just made our relation bi-directional. Note that the inverse relation does not have a @JoinTable. @JoinTable must be only on one side of the relation.
Bi-directional relations allow you to join relations from both sides using QueryBuilder:
1
const categoriesWithQuestions = await connection
2
.getRepository(Category)
3
.createQueryBuilder("category")
4
.leftJoinAndSelect("category.questions", "question")
5
.getMany();
Copied!

Many-to-many relations with custom properties

In case you need to have additional properties in your many-to-many relationship, you have to create a new entity yourself. For example, if you would like entities Post and Category to have a many-to-many relationship with an additional order column, then you need to create an entity PostToCategory with two ManyToOne relations pointing in both directions and with custom columns in it:
1
import { Entity, Column, ManyToOne, PrimaryGeneratedColumn } from "typeorm";
2
import { Post } from "./post";
3
import { Category } from "./category";
4
​
5
@Entity()
6
export class PostToCategory {
7
@PrimaryGeneratedColumn()
8
public postToCategoryId!: number;
9
​
10
@Column()
11
public postId!: number;
12
​
13
@Column()
14
public categoryId!: number;
15
​
16
@Column()
17
public order!: number;
18
​
19
@ManyToOne(() => Post, post => post.postToCategories)
20
public post!: Post;
21
​
22
@ManyToOne(() => Category, category => category.postToCategories)
23
public category!: Category;
24
}
Copied!
Additionally you will have to add a relationship like the following to Post and Category:
1
// category.ts
2
...
3
@OneToMany(() => PostToCategory, postToCategory => postToCategory.category)
4
public postToCategories!: PostToCategory[];
5
​
6
// post.ts
7
...
8
@OneToMany(() => PostToCategory, postToCategory => postToCategory.post)
9
public postToCategories!: PostToCategory[];
Copied!