You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Sequelize+TypeScript+NestJS筛选含全部指定Filters的Products?

筛选满足全部指定筛选条件的产品

现有Products与Filters两张表,二者为一对多关联关系(一个产品对应多个筛选条件),需求是筛选出拥有所有指定筛选条件的产品。

Filters表示例数据

namegroupproductId
value1group11
value2group21
value2group22

筛选参数示例

const filters = {
  group1: 'value1',
  group2: 'value2',
  // 可扩展更多筛选条件
};

await this.productService.fillAll({
  include: {
    [Op.and]: Object.entries(filters).map(([group, value]) => ({
      group,
      value
    })),
  }
})

// 最终转换后的筛选条件数组:[{group: 'group1', value: 'value1'},{group: 'group2', value: 'value2'}]

期望执行查询后仅返回productId为1的产品,因为productId为2的产品缺少{group: 'group1', value: 'value1'}这一必要筛选条件。

现有实现代码片段

...

  private getFilters(filters: { [key: string]: string }) {
    return {
      [Op.and]: Object.entries(filters).map(([group, value]) => ({
        group,
        value
      })),
    };
  }

  ...

  if (filters) {
    findOptions.include = [
      {
       model: Filters,
       where: this.getFilters(filters),
      },
    ];
  }

  findOptions.offset = (offset - 1) * limit;
  findOptions.limit = limit;
  findOptions.order = [['createdAt', 'DESC']];
  
  const { count, rows: products } =
      await this.productRepository.findAndCountAll(findOptions);


  ...

内容的提问来源于stack exchange,提问作者Anton Duditsky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 18:22:58