Search code examples
sqltypescriptnestjstypeorm

Populaing a query in Typeorm


Can anyone help me to know how to populate a query in typeorm. Like I have this entity

@Entity('users')
export class User extends BaseEntity {
  @Column()
  userName : string;
  
  @Column()
  email : string;

  @OneToMany(() => UserFollowing, (userFollowing) => userFollowing.followee)
  followers: User[];

  @OneToMany(() => UserFollowing, (userFollowing) => userFollowing.follower)
  followees: User[];
}

@Entity('user_followings')
export class UserFollowing extends FakeBaseEntity {
  @JoinColumn({ name : 'follower_id' })
  @ManyToOne(() => User, user => user.followees)
  follower : User;

  @JoinColumn({ name : 'followee_id' })
  @ManyToOne(() => User, user => user.followers)
  followee : User;
}

Now to get all the followers and followees of a particular userid

Here are my two approaches : both giving same output

const info = await this.userRepo
      .createQueryBuilder('userFollowing')
      .select()
      .leftJoinAndSelect('userFollowing.followers','followers')
      .leftJoinAndSelect('userFollowing.followees', 'followees')
      .where('userFollowing.id = :userid', { userid })
      .getMany()

return info;
------------------------------------------------------------
const info = this.userRepo.find({
      where: {
        id : userid,
      },
      relations: ["followers", "followees"],
    })
return info;

output I am recieving : and I want all the info about followers and followees

{
    "id": "e8651d4f-3c7b-4f5a-8205-7370b107d98c",
    "userName": "something",
    "email" : "[email protected]",
    "followers": [
      {
        "id": "f54b8574-10ea-4133-85bd-5f8fcda4eeb9",
        "createdAt": "2021-08-12T03:58:39.198Z",
        "updatedAt": "2021-08-12T03:58:39.198Z"
      }
    ],
    "followees": [
      {
        "id": "eb2cb728-a1c0-4bea-9230-712827c714c7",
        "createdAt": "2021-08-12T03:59:32.260Z",
        "updatedAt": "2021-08-12T03:59:32.260Z"
      }
    ]
  }

Solution

  • If I have understood your question correctly, then what you are looking for is to get the data of followers and followees as well.

    You can easily achieve this with the find function.

    This is how your query should look:

    const info = this.userRepo.find({
      where: {
        id : userid,
      },
      relations: ["followers", "followees", "followers.follower", "followees.followee"],
    })
    

    As you can see, I have passed two more string values in the relations. Using this, it will load the sub-relations as well (stated in the TypeORM Find Options).

    You can achieve the same using query builder as well by adding more .leftJoinAndSelect method chain.

    External Links: