当对象值具有不同类型时,通过多个查询参数过滤数据

Filter data by multiple Query Params when object values have different types

几天来我一直在努力让这个东西发挥作用,我觉得我已经准备好了,但我不知道我还缺少什么。

我的对象在为我服务时看起来像这样:

GetAllDataFilterDto {
  orgId: 12345,
  status: [ 'approved', 'pending' ],
}

我正在使用 typeorm,这是我的查询:

  protected getAll(filter: GetAllDataFilter): SelectQueryBuilder<EntityName> {
    const qb = Repository<EntityName>
      .createQueryBuilder('entityName')
      .select([
        'entityName.id',
        'entityName.status',
        'entityName.orgId',
      ])
      .groupBy('entityName.id')
      .where(this.getFilterConditions(filter));

    return qb;
  }

我的查询使用了 getMany() 但在不同的文件中,这就是为什么它不包含在此函数中的原因。

这是我遇到问题的地方,我当前的过滤函数如下所示:

  protected getFilterConditions(filter: GetAllDataFilter) {
    return _.pickBy(filter, (value, key) => value !== undefined && this.entityProperties.has(key));
  }

entityProperties 是一个如下所示的集合:

Set {
'id',
'status',
'orgId'
}

目前,此过滤器适用于数字,如果我的数组只有一个值,但当我添加两个值时,它 returns 错误

trace: QueryFailedError: Operand should contain 1 column(s)

我的最终目标是过滤我返回的数据,即使有可选参数,所以所有带有批准或待定的状态列都会被返回,但我仍然需要能够同时按 orgId 进行过滤。

请让我知道是否还有更多需要包括的内容,谢谢。

我认为问题可能出在您的 queryBuilder 上的 .where,它假设采用 1 个参数(换句话说,仅检查 1 个字段的条件),然后您可以添加.andWhere 对另外 1 个参数添加过滤器。

From the docs :

对于单个 .where 条件:

Adding a WHERE expression is as easy as:

createQueryBuilder("user").where("user.name = :name", { name: "Timber" })

对于多个 .where 条件:

You can add AND into an existing WHERE expression:

createQueryBuilder("user")
    .where("user.firstName = :firstName", { firstName: "Timber" })
    .andWhere("user.lastName = :lastName", { lastName: "Saw" })