TypeORM中如何结合QueryBuilder?

How to combine QueryBuilder in TypeORM?

例如:

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

当option.productId的值为''时,我要查询全部

现在我的代码是这样的:

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

但是当where query太多的时候,代码就很烂了像:

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

在TypeORM中结合QueryBuilder有没有更好的方法?

你可以做这样的东西

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();