【问题标题】:How to combine QueryBuilder in TypeORM?如何在 TypeORM 中结合 QueryBuilder?
【发布时间】:2021-06-16 01:02:44
【问题描述】:

例如:

    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 查询太多的时候,代码就这么糟糕了:

    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?

【问题讨论】:

  • “但是什么时候where查询太多?”
  • @AWebb 你好,我已经编辑了新的演示代码。
  • 无论您使用 TypeORM 做什么,您都将重构您已有的内容。就个人而言,我会为每个场景创建不同的查询,然后从客户端有条件地调用它们。这样,每次调用此查询时,您都不会运行条件。而是针对每个特定场景的客户端条件请求。

标签: nestjs typeorm


【解决方案1】:

你可以做这样的事情

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

【讨论】:

  • TY 为您提供帮助。这是使用它的最佳方式。
猜你喜欢
  • 2021-06-18
  • 1970-01-01
  • 1970-01-01
  • 2021-04-28
  • 1970-01-01
  • 2020-10-24
  • 1970-01-01
  • 2022-06-10
  • 1970-01-01
相关资源
最近更新 更多