如何在实体中建立自我关系?

时间:2020-11-06 11:21:58

标签: typeorm

我有实体文件:

@Entity('groups')
export class Groups {
  @PrimaryGeneratedColumn({ type: 'integer', name: 'id' })
  id: number;

  @Column({ type: 'int', nullable: true })
  parentid: number | null;

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

  @Column({ type: 'varchar', nullable: true, length: 4096 })
  description?: string;
}

并且我想成为父代的id是外键,就像这张图片一样:

enter image description here

也许有人知道我该怎么做?

感谢答案。

1 个答案:

答案 0 :(得分:1)

基于此link,有多种方法可以做到这一点,但我个人建议您这样做:

@Entity('groups')
export class Groups {
  @PrimaryGeneratedColumn({ type: 'integer', name: 'id' })
  id: number;

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

  @Column({ type: 'varchar', nullable: true, length: 4096 })
  description?: string;

  @Column({ nullable: true })
  parentId: number;

  @ManyToOne((type) => Groups, (groups) => groups.children)
  @JoinColumn({ name: 'parentId' })
  parent: Groups;

  @OneToMany((type) => Groups, (groups) => groups.parent)
  children: Groups[];
}