Laravel GroupBy 关系列计数

问题描述 投票:0回答:1

我知道以前有人问过类似的问题,但我找不到答案。 我的问题 一个Order有多个Products。产品有“类别”列。 如何查找每个类别的订单数量? 得到结果 ?:

[
    "ctegory_4" => 55, //(Orders count)
    "ctegory_2" => 22,
    "ctegory_3" => 11
]

这很接近,但我需要以某种方式 pluck 和 groupBy 结果...

$ordersPerCategories = Order::with(['products' => function($q){
     $q->select('category', DB::raw('count(*) as total'), 'product_id');
   }])->get();
laravel count sql-order-by relationship
1个回答
0
投票

原来有个回答,不知道为什么被删了……
答案:

$orders = DB::table('orders')
    ->join('order_product', 'orders.id', '=', 'order_product.order_id')
    ->join('products', 'products.id', '=', 'order_product.product_id')
    ->select('products.category', DB::raw('count(DISTINCT orders.id) as total'))
    ->groupBy('products.category')
    ->orderBy('total', "DESC")
    ->pluck('total', 'category');
© www.soinside.com 2019 - 2024. All rights reserved.