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

Symfony新手求助:获取不同商品及其最大category_id的SQL查询

解决方案

首先,你的原SQL没有实现商品去重,也没处理“获取每个商品对应最大category_id”的需求,调整后的SQL如下:

SELECT p.title, p.price, s.*, p.image, MAX(pc.category_id) AS max_category_id
FROM shopcart s
JOIN product p ON s.productid = p.id
JOIN product_category pc ON pc.product_id = p.id
WHERE s.userid = 4
GROUP BY p.id, p.title, p.price, s.id, s.productid, s.userid, s.quantity, p.image

关键说明:

  • 替换了旧的逗号表连接方式,用显式JOIN语法更清晰规范
  • 用MAX(pc.category_id)聚合函数拿到每个商品对应的最大分类ID
  • 通过GROUP BY按商品和购物车的唯一标识字段分组,确保每个商品只返回一条结果,同时保留购物车的相关数据(注意:GROUP BY需要包含所有非聚合的查询字段,可根据你实际表的字段调整)

如果是在Symfony里用Doctrine实现,参考以下Query Builder代码:

// 假设在ShopcartRepository中
public function getCartItemsWithMaxCategory(int $userId)
{
    return $this->createQueryBuilder('s')
        ->select('p.title, p.price, s, p.image, MAX(pc.categoryId) AS maxCategoryId')
        ->join('s.product', 'p') // 这里的关联名要和你Entity里定义的一致
        ->join('p.productCategories', 'pc') // 同理,对应Product和ProductCategory的关联属性
        ->where('s.userId = :userId')
        ->setParameter('userId', $userId)
        ->groupBy('p.id', 's.id', 'p.title', 'p.price', 'p.image')
        ->getQuery()
        ->getResult();
}

内容的提问来源于stack exchange,提问作者Muharrem Sarıgöl

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 08:18:35