Search code examples
node.jsnestjstypeorm

How can i Add Where Condition on a Joined Table in TypeORM & NestJS?


I am working on a project using TypeORM, and I'm trying to add a WHERE condition on a column in a joined table. I have a Reservation entity with a many-to-one relationship to a Listing entity. Here is the relevant code snippet:

  findAllByUserId(userId: number) {
    return this.reservationRepository.find({
      relations: ['listing', 'listing.favourite'],
      where: { user_id: userId }
    });
  }

I am facing issues trying to add a WHERE condition on a column in the listing table. I'd appreciate any guidance on how to correctly add a condition to the joined table in TypeORM.


Solution

  • Try something like below :

      findAllByUserIdWithCondition(userId: number, conditionValue: string): Promise<Reservation[]> {
        return this.reservationRepository
          .createQueryBuilder('reservation')
          .innerJoinAndSelect('reservation.listing', 'listing')
          .innerJoinAndSelect('listing.favourite', 'favourite')
          .where('reservation.user_id = :userId', { userId })
          .andWhere('listing.columnName = :conditionValue', { conditionValue })
          .getMany();
      }
    }