如何在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 (将#修改为@)