Laravel:如何按商品分类统计对应订单数量?
需求说明
已知Order模型与Product模型为一对多关联,Product模型包含category字段。需统计每个商品分类对应的订单数量,期望结果格式如下:
[ "category_4" => 55, // 订单数量 "category_2" => 22, "category_3" => 11 ]
现有代码未实现分组统计,需要调整:
$ordersPerCategories = Order::with(['products' => function($q){ $q->select('category', DB::raw('count(*) as total'), 'product_id'); }])->get();
解决方案
你当前使用with()预加载关联数据的方式无法直接完成分组统计需求,以下是两种可行的实现方式:
方式一:从Product模型发起关联查询
$categoryOrderCount = Product::select('category', DB::raw('COUNT(DISTINCT order_id) as total')) ->join('orders', 'products.order_id', '=', 'orders.id') // 请根据实际模型关联的外键字段调整 ->groupBy('category') ->pluck('total', 'category');
方式二:从Order模型发起关联查询
$categoryOrderCount = Order::select('products.category', DB::raw('COUNT(orders.id) as total')) ->join('products', 'orders.id', '=', 'products.order_id') // 请根据实际模型关联的外键字段调整 ->groupBy('products.category') ->pluck('total', 'products.category');
两种方式最终都会返回你需要的键值对数组,其中键为商品分类名,值为对应分类的订单数量。注意要确保join语句中的外键字段和表名与你的实际数据库结构匹配。
内容的提问来源于stack exchange,提问作者Sezz Fess
相关产品推荐
相关产品推荐

