【发布时间】:2020-08-13 11:43:59
【问题描述】:
【问题讨论】:
标签: typescript many-to-many relationship nestjs typeorm
【问题讨论】:
标签: typescript many-to-many relationship nestjs typeorm
我找到了解决方案;它实际上是写在 Tyrm 的文档中 https://github.com/typeorm/typeorm/blob/master/docs/many-to-many-relations.md#many-to-many-relations-with-custom-properties
与自定义属性的多对多关系 如果您需要为多对多关系添加其他属性,则必须自己创建一个新实体。例如,如果您希望实体 Post 和 Category 与附加订单列具有多对多关系,则需要创建具有两个指向两个方向的 ManyToOne 关系和其中的自定义列的实体 PostToCategory:
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(type => Post, post => post.postToCategories)
public post!: Post;
@ManyToOne(type => Category, category => category.postToCategories)
public category!: Category;
}
此外,您还必须向 Post 和 Category 添加如下关系:
// category.ts
...
@OneToMany(type => PostToCategory, postToCategory => postToCategory.category)
public postToCategories!: PostToCategory[];
// post.ts
...
@OneToMany(type => PostToCategory, postToCategory => postToCategory.post)
public postToCategories!: PostToCategory[];
【讨论】: