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. Question can have multiple categories, and each category can have multiple questions.
As you can see 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:
When using FindOptions you don't need to specify eager relations - they are always automatically loaded.
bi-directional relations
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:
In case you need to have additional properties to 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 additional order column, you need to create entity PostToCategory with two ManyToOne relations pointing in both directions and custom columns in it:
import { Entity, Column, ManyToOne, PrimaryGeneratedColumn } from "typeorm";
import { Post } from "./post";
import { Category } from "./category";
@Entity()
export class PostToCategory {
@PrimaryGeneratedColumn()
public postToCategoryId!: number;
@Column()
public postId!: number;
@Column()
public categoryId!: number;
@Column()
public order!: number;
@ManyToOne(() => Post, post => post.postToCategories)
public post!: Post;
@ManyToOne(() => Category, category => category.postToCategories)
public category!: Category;
}
Additionally you will have to add a relationship like the following to Post and Category: