【问题标题】:3 way many-to-many typeOrm3路多对多typeOrm
【发布时间】:2020-08-13 11:43:59
【问题描述】:

有没有办法在typeOrm中实现3路多对多关系

3 路多对多关系的示例如下

3 way many-to-many relationship

【问题讨论】:

    标签: typescript many-to-many relationship nestjs typeorm


    【解决方案1】:

    我找到了解决方案;它实际上是写在 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[];
    

    【讨论】:

    • 这不是多对多的 3 方式,而是自定义属性的两种方式。
    • 你是对的,它不是,但它是 3 路多对多关系的唯一解决方案
    • 但这如何提供 3 种方式?我只看到这里引用了 2 个实体。如果您有一些显示此工作的代码,请尽可能发布。
    猜你喜欢
    • 2021-05-18
    • 2020-08-29
    • 2020-06-29
    • 2020-09-01
    • 2020-12-03
    • 2021-04-23
    • 2020-09-27
    • 2021-12-26
    • 1970-01-01
    相关资源
    最近更新 更多