Self-Referencing ManyToMany Relationship TypeORM

后端 未结 2 1462
半阙折子戏
半阙折子戏 2021-02-14 17:16

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

2条回答
  •  遥遥无期
    2021-02-14 17:56

    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).

提交回复
热议问题