Self-Referencing ManyToMany Relationship TypeORM

后端 未结 1 751
迷失自我
迷失自我 2021-02-14 17:40

I have just started using TypeORM and I\'m struggling getting the following relationship to work:

User->Friends, whereas a Friend is also a User Object. My getters, getF

1条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-14 18:04

    You can self-reference your relations. Here is an example of a simple directed graph (aka a node can have a parent and multiple children).

    @Entity()
    export class Service extends BaseEntity {
    
      @PrimaryGeneratedColumn()
      id: number;
      
      @Column()
      @Index({ unique: true })
      title: string;
    
      @ManyToOne(type => Service, service => service.children)
      parent: Service;
    
      @OneToMany(type => Service, service => service.parent)
      children: Service[];
    }
    

    An important note to keep in mind is that these relations are not auto loaded when reading an object from the DB with find* functions.

    To actually load them, you have to use query builder at the moment and join them. (You can join multiple levels.) An example:

    let allServices = await this.repository.createQueryBuilder('category')
      .andWhere('category.price IS NULL')
      .innerJoinAndSelect('category.children', 'product')
      .leftJoinAndSelect('product.children', 'addon')
      .getMany();
    

    Please note how I used different names to reference them (category, product, and addon).

    0 讨论(0)
提交回复
热议问题