diff --git a/docs/faq.md b/docs/faq.md index 62236a2ac7..c63cfd80e9 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -131,7 +131,7 @@ join column / junction table settings, like join column name or junction table n It's not possible to add extra columns into a table created by a many-to-many relation. You'll need to create a separate entity and bind it using two many-to-one relations with the target entities (the effect will be same as creating a many-to-many table), -and add extra columns in there. +and add extra columns in there. You can read more about this in [Many-to-Many relations](./many-to-many-relations.md#many-to-many-relations-with-custom-properties). ## How to use TypeORM with a dependency injection tool? diff --git a/docs/many-to-many-relations.md b/docs/many-to-many-relations.md index 3070692b50..1ade4bd27b 100644 --- a/docs/many-to-many-relations.md +++ b/docs/many-to-many-relations.md @@ -169,3 +169,40 @@ const categoriesWithQuestions = await connection .leftJoinAndSelect("category.questions", "question") .getMany(); ``` + +## many-to-many relations with custom properties + +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 a `createdAt` property +associated to it you have to create entity `PostToCategory` like the following: + +```typescript +import { Entity, Column, ManyToOne, PrimaryGeneratedColumn } from "typeorm"; +import { Post } from "./post"; +import { Category } from "./category"; + +@Entity() +export class PostToCategory { + @PrimaryGeneratedColumn() + public postToCategoryId!: number; + + public postId!: number; + public categoryId!: number; + + @Column() + public order!: number; + + @ManyToOne(type => Post, post => post.postToCategories) + public post!: Post; + + @ManyToOne(type => Category, category => category.postToCategories) + public category!: Category; +} +``` + +Additionally you will have to add a relationship like the following to `Post` and `Category`: + +```typescript +@OneToMany((type) => PostToCategory, (postToCategory) => postToCategory.post) +public postToCategories!: PostToCategory[]; +```