如何使用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
相关产品推荐
相关产品推荐

