ugabuga77
ugabuga77

Reputation: 791

TypeOrm QueryBuilder Multiple relations to one table

Thanks for reading and trying to help in advance!

I have a following problem. On my "Offer" entity there are multiple relations to "User", as follows:

  @ManyToOne(() => User, (user) => user.offers, { nullable: false })
  owner: User;
  @ManyToMany(() => User, (user) => user.participates, {
    nullable: true,
    cascade: true,
  })
  @JoinTable()
  participants: User[];
  @ManyToMany(() => User, (user) => user.applied, {
    nullable: true,
    cascade: true,
  })
  @JoinTable()
  applicants: User[];

Question is - how do I load all of these relations with query builder? When I use leftJoinAndSelect it throws an error saying: "QueryFailedError: table name "user" specified more than once"

return await this.getOffersBaseQuery()
  .andWhere('o.id = :id', {
    id,
  })
  .leftJoinAndSelect('o.skill', 'skill')
  .leftJoinAndSelect('o.owner', 'user')
.leftJoinAndSelect('o.participants', 'user')
  .select([
    'o',
    'skill.id',
    'skill.name',
    'user.username',
    'user.email',
    'user.id',
  ])
  .getOne();

Just in case - base query:

private getOffersBaseQuery() {
    return this.offerRepository.createQueryBuilder('o').orderBy('o.id', 'DESC');
  }

Upvotes: 0

Views: 2394

Answers (1)

ugabuga77
ugabuga77

Reputation: 791

Nevermind, the answer to this question was just in TypeORM docs. All I had to do was to use different allias for

.leftJoinAndSelect('o.participants', 'user')

which I did with:

.leftJoinAndSelect('o.participants', 'participants')

Feel really stupid now.

Upvotes: 1

Related Questions