微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在TypeORM中使用外键引用自身递归外键保存实体

如何解决如何在TypeORM中使用外键引用自身递归外键保存实体

我是 TypeORM 的新手,我陷入了鸡/蛋场景。我有以下实体:

@Index("institutes_pkey",["idInstitute"],{ unique: true })
@Entity("institutes",{ schema: "public" })
export class Institutes {
  @PrimaryGeneratedColumn({ type: "bigint",name: "id_institute" })
  id_institute: string;

  @Column("text",{ name: "name" })
  name: string;

  @Column("text",{ name: "description" })
  description: string;

  @ManyToOne(() => Institutes,(institutes) => institutes.institutes)
  @JoinColumn([{ name: "id_grupo",referencedColumnName: "idInstitute" }])
  id_group: Institutes;

  @OnetoMany(() => Institutes,(institutes) => institutes.id_group)
  institutes: Institutes[];
}

child_institutes 可以归入更大的father_institute 之下。

在这种情况下,id 组将如下所示:

father_institute.id_group = father_institute.id_institute

child_institutes.id_group = father_institute.id_institute

如果一个机构不属于任何组,它的 id_group 等于它的 id_institute(与父亲案例相同)。这就是我的问题,当我需要保存一个 father_institute 时,它的 FK 引用了我试图保存的同一个对象。在这种情况下我该怎么办?

我想出了一个解决方法,在 Psql 中创建一个序列并使用该序列设置 id_institute,然后将 id_group 的认值设置为该序列的当前值。但是有没有更好的解决方案?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。