【问题标题】:How to create an entity that would relate to another one of the same type (recursive entities)如何创建与另一个相同类型的实体(递归实体)相关的实体
【发布时间】:2020-06-08 23:42:30
【问题描述】:

简而言之:我有一个名为Section 的实体,它应该包含一个名为Subsection 的字段。每个部分可以有许多子部分,一个子部分只能属于一个部分。所以我们在这里有Many2One。这个类看起来像这样(我只复制了几个字段):

@Entity('section')
export class SectionEntity {
    @PrimaryGeneratedColumn('increment')
    id: number;

    @Column({
        type: 'int',
        name: 'template_id',
        nullable: true,
    })
    templateId: number;

    @Column({
        type: 'varchar',
        name: 'name',
    })
    name: string;

    @Column({
        type: 'boolean',
        name: 'is_base_template',
    })
    isBaseTemplate: boolean;
}

但我需要添加另一个类型为SectionEntity 的字段subsections。所以在这种情况下,它看起来像一个递归类型。

我该怎么做,然后会是什么样的关系(装饰器)?

【问题讨论】:

    标签: nestjs


    【解决方案1】:

    我假设这实际上是来自装饰实体的 Typeorm 问题。Typeorm 中有对它的支持,你可以找到一个很好的例子here。 在这种情况下,它看起来像这样:

    @Entity('section')
    export class SectionEntity {
       @PrimaryGeneratedColumn('increment')
       id: number;
    
       @Column({
          type: 'int',
          name: 'template_id',
          nullable: true,
       })
       templateId: number;
    
       @Column({
          type: 'varchar',
          name: 'name',
       })
       name: string;
    
       @Column({
          type: 'boolean',
          name: 'is_base_template',
       })
       isBaseTemplate: boolean;
    
       @ManyToOne(type => SectionEntity, section => section.subsections)
       parentSection: SectionEntity;
    
       @OneToMany(type => SectionEntity, section => section.parentSection)
       subsections: SectionEntity[];
    }
    

    【讨论】:

    • 它就像一个魅力!太棒了,再次感谢你。你拯救了我的一天,伙计!
    • 请看一下我的另一个问题,与这里讨论的问题有关吗?这是链接stackoverflow.com/questions/62314903/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    • 2018-01-16
    • 1970-01-01
    • 2013-03-03
    • 2016-07-14
    • 1970-01-01
    • 2020-09-14
    相关资源
    最近更新 更多