发布于 2020-04-29 11:44:38
我找到了一个解决方案;它实际上是写在typorm的文档https://github.com/typeorm/typeorm/blob/master/docs/many-to-many-relations.md#many-to-many-relations-with-custom-properties中的
多到多的关系与自定义属性,如果你需要有额外的属性,你的多到多的关系,你必须自己创建一个新的实体。例如,如果希望实体Post和类别与附加的order列具有多到多的关系,则需要创建实体PostToCategory,其中两个ManyToOne关系指向方向和自定义列:
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.ts
...
@OneToMany(type => PostToCategory, postToCategory => postToCategory.category)
public postToCategories!: PostToCategory[];
// post.ts
...
@OneToMany(type => PostToCategory, postToCategory => postToCategory.post)
public postToCategories!: PostToCategory[];
https://stackoverflow.com/questions/61500908
复制