Self-Referencing ManyToMany Relationship TypeORM

后端 未结 2 1461
半阙折子戏
半阙折子戏 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).

    0 讨论(0)
  • 2021-02-14 18:11

    I hope someone understands my question

    Yeah, here is the problem. I don't know what are trying to do. Friend is a separate class or it's still User->User[] relation?

    Maybe this will help you: https://typeorm.github.io/tables-and-columns.html#closure-table

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