Search code examples
nestjstypeorm

How to combine QueryBuilder in TypeORM?


for example:

    const tempResult = await this.userRepository
    .createQueryBuilder('user')
    .leftJoinAndSelect('user.products', 'product')
    .where('product.id = :productId', { productId: option.productId })
    .getManyAndCount();

when the option.productId's value is '',I want query all.

now my code is like this:

    let tempResult = null;
    if (option.productId) {
      tempResult = await this.userRepository
        .createQueryBuilder('user')
        .leftJoinAndSelect('user.products', 'product')
        .where('product.id = :productId', { productId: option.productId })
        .getManyAndCount();
    } else {
      tempResult = await this.userRepository.createQueryBuilder('user').getManyAndCount();
    }

But when where query is too much,the code is so bad like:

    let tempResult = null;
    if (option.productId && option.organizationId) {
      tempResult = await this.userRepository
        .createQueryBuilder('user')
        .leftJoinAndSelect('user.products', 'product')
        .leftJoinAndSelect('user.organization', 'organization')
        .where('product.id = :productId', { productId: option.productId })
        .where('organization.id = :organizationId', { organizationId: option.organizationId })
        .getManyAndCount();
    } else if (option.productId) {
      tempResult = await this.userRepository
        .createQueryBuilder('user')
        .leftJoinAndSelect('user.products', 'product')
        .where('product.id = :productId', { productId: option.productId })
        .getManyAndCount();
    } else if (option.organizationId) {
      tempResult = await this.userRepository
        .createQueryBuilder('user')
        .leftJoinAndSelect('user.organization', 'organization')
        .where('organization.id = :organizationId', { organizationId: option.organizationId })
        .getManyAndCount();
    } else {
      tempResult = await this.userRepository.createQueryBuilder('user').getManyAndCount();
    }

Is there a better way to combine QueryBuilder in TypeORM?


Solution

  • you can make something like this

    const query = this.userRepository.createQueryBuilder('user');
    
    if (option.productId) {
      query
      .leftJoinAndSelect('user.products', 'product')
      .where('product.id = :productId', { productId: option.productId })
    }
    
    if (option.organizationId) {
     query
     .leftJoinAndSelect('user.organization', 'organization')
     .where('organization.id = :organizationId', { organizationId: option.organizationId });
    }
    
    tempResult = await query.getManyAndCount();