简体   繁体   中英

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');
  }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM