Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: add explanation ManyToMany with custom properties #4308

Merged
merged 3 commits into from
Jun 30, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/faq.md
Original file line number Diff line number Diff line change
Expand Up @@ -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?

Expand Down
37 changes: 37 additions & 0 deletions docs/many-to-many-relations.md
Original file line number Diff line number Diff line change
Expand Up @@ -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[];
```