Search code examples
typeorm

How to create self relation in entity?


I have entity file:

@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;
}

and I want to parentid will be have foreign key to id, like on this image:

enter image description here

May be someone know how I can do that?

Thanks for answers.


Solution

  • Based on this link, there are multiple ways to do that but personally I suggest you this:

    @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[];
    }