【问题标题】:Laravel multiple counts with conditions from one tableLaravel 多个计数,条件来自一张表
【发布时间】:2021-05-27 13:52:03
【问题描述】:

我有一个orders 表,需要根据具体情况合并多个计数。

目前我有 3 个查询:

$orderCount = Order::count();
$newOrderCount = Order::where('status', '=', 'new')->count();
$completedOrderCount = Order::where('status', '=', 'completed')->count();

如何将其组合成 1 个查询?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    不是用雄辩的,而是我想到的第一个解决方案

    DB::table('orders')
        ->select(DB::raw('count(*) as order_count'))
        ->addSelect(DB::raw('sum(case when status = "new" then 1 else 0 end) as new_orders_count'))
        ->addSelect(DB::raw('sum(case when status = "completed" then 1 else 0 end) as completed_orders_count'))
        ->get();
    

    或者用集合来做:

    $orders = Order::all();
    $orderCount = $orders->count();
    $newOrderCount = $orders->where('status', '=', 'new')->count();
    $completedOrderCount = $orders->where('status', '=', 'completed')->count();
    

    【讨论】:

      【解决方案2】:

      一个冗长的解决方案,但也可以解决问题。

      $orders = Order::all(['id'])->toArray();
      $orderCount = 0;
      $newOrderCount = 0;
      $completedOrderCount = 0;
      
      array_map(function ($o) use (&$orderCount, &$newOrderCount, &$completedOrderCount) {
          $orderCount++;
      
          if($o['status'] === 'new')
              $newOrderCount++;
      
          if($o['status'] === 'completed')
              $completedOrderCount++;
      
      }, $orders);
      

      【讨论】:

      • $orders.each 看起来有点不标准。这是故意的还是错字?
      • @shaedrich,哎呀,我的错。将Illuminate\Database\Eloquent\Collection 误认为Illuminate\Support\Collection 。固定的!。谢谢指正。?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-01
      • 2018-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-29
      相关资源
      最近更新 更多