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

如何使用Sequelize查询指定店铺中各商品的最高与最低价格?

修改方案

要实现指定店铺中每个商品的最高与最低价格,需要对现有代码做3处关键修改:

1. 筛选指定店铺

在models.shop.findAll的配置中添加where条件,指定目标店铺的唯一标识(比如ID或名称),确保只查询该店铺的数据:

where: { id: targetShopId } // 替换targetShopId为实际要查询的店铺ID

2. 移除单个商品的限制(按需选择)

现有代码在Product的include中加了where: { id: productId },这会仅查询单个商品。如果需要获取该店铺下所有商品的价格数据,直接移除这个where条件;如果是查询指定店铺的指定商品,则保留该条件。

3. 按商品分组计算价格聚合

在price_reads的include配置中添加group属性,确保MAX/MIN价格是按每个商品(对应shop_has_product的关联记录)单独计算,而非所有商品的价格聚合:

group: ['shop_has_products.id', 'Product.id']

修改后的完整代码

// 替换为实际要查询的店铺ID
const targetShopId = 123;

const products = await models.shop.findAll({
  attributes: ['name', 'address'],
  // 新增:筛选指定店铺
  where: { id: targetShopId },
  include: [
    {
      model: models.shop_has_product,
      as: 'shop_has_products',
      include: [
        {
          model: models.product,
          as: 'Product'
          // 移除:单个商品的限制(如需查询所有商品)
          // where: { id: productId }
        },
        {
          model: models.price_read,
          as: 'price_reads',
          attributes: [
            [sequelize.fn('MAX', sequelize.col('price')), 'maxPrice'],
            [sequelize.fn('MIN', sequelize.col('price')), 'minPrice']
          ],
          // 新增:按商品分组计算聚合值
          group: ['shop_has_products.id', 'Product.id']
        }
      ]
    },
    {
      model: models.street,
      as: 'Street',
      attributes: ['name'],
      include: [
        {
          model: models.city,
          as: 'City',
          where: { name: city }
        }
      ]
    }
  ]
});

补充说明

  • 如果店铺的唯一标识是名称而非ID,可将where条件改为where: { name: '目标店铺名称' },只要能精准定位单个店铺即可。
  • 分组字段shop_has_products.id用于确保每个店铺-商品关联记录单独计算价格,加上Product.id是为了兼容Sequelize的关联分组规则,避免报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 18:46:23