【问题标题】:Laravel multiple count in 1 QueryLaravel 1 个查询中的多个计数
【发布时间】:2019-03-30 19:46:29
【问题描述】:

我是这个框架的新手,我不知道如何使用 db::raw 计数和别名对其进行优化,并使用 @foreach 将其显示到我的 Blade.php 中

我正在尝试优化我的代码,我的目标是计算pallet_conditions 并将其存储到我的别名中,我不想像我对这段代码所做的那样一一计算

这是我的代码没有优化:

//computing the total rapairable
$repairable_total = DB::table('liip_psrm_items')
->where('psrm_items_id', '=' , $psrm_maintenance->id)
->where('pallet_condition', '=', 1)
->count();
//REPAIRABLE

//computing the total good pallets
$good_total = DB::table('liip_psrm_items')
->where('psrm_items_id', '=' , $psrm_maintenance->id)
->where('pallet_condition', '=', 0)
->count();
//GOOD

这是代码,我想学习的。只是为了最小化,并使用别名

$result = DB::table('liip_psrm_items')
->select(DB::raw('COUNT(liip_psrm_items.pallet_condition = 0 ) AS condition_1',
                 'COUNT(liip_psrm_items.pallet_condition = 1 ) AS condition_2'))                      
                ->where('psrm_items_id', '=' , $psrm_maintenance->id)
                ->get();

【问题讨论】:

  • 你的 Laravel 代码对我来说看起来不错。您的实际问题是什么?

标签: php laravel eloquent laravel-query-builder laravel-4.2


【解决方案1】:

尝试像这样传递闭包:

$results = DB::table('liip_psrm_items')
->where('psrm_items_id', '=' , $psrm_maintenance->id)
->where(function($query){
   $query->where('pallet_condition', 1)
      ->orWhere('pallet_condition', 0);
})->count();

【讨论】:

    【解决方案2】:

    您不能对两个不同的结果使用一个查询,这两个结果具有完全相反的条件。

    案例 1. 您正在尝试计算托盘条件 = 1 的项目;

    案例 2。您正在尝试计算pallet_condition = 0 的项目;

    现在你想将这两种情况合并到一个查询中,这是不可能的......

    因此,对于这两种情况,您必须使用单独的查询(您已经做过的)

    或者您可以使用单个查询来获取所有项目,然后使用 PHP 将它们分开。

    喜欢:

    $total_items = DB::table('liip_psrm_items')
       ->where('psrm_items_id', '=' , $psrm_maintenance->id)
       ->get();
    
    $repairable_count = count(array_filter($total_items, function($item){
       return (bool)$item->pallet_condition;
    }));
    
    $good_count = count(array_filter($total_items, function($item){
       return !(bool)$item->pallet_condition; //just inverse of the above condition
    }));
    

    我希望这可能会有所帮助。

    【讨论】:

    • 感谢@jaskaran 的建议。上面的回答jonkie解决了我的问题
    【解决方案3】:

    你可以,先group by,然后得到count

    喜欢:

    DB::table('liip_psrm_items')
      ->groupBy('pallet_condition')
      ->select('pallet_condition', DB::raw('count(*) as total'))
      ->get();
    
    

    【讨论】:

      【解决方案4】:

      为了在多个条件下计数,我使用了这种方法

       $lastMonthInvoices = Invoice::select(DB::raw("(COUNT(*)) as count"), DB::raw('SUM(total) as total'),'status')
              ->whereDate('created_at', '>', Carbon::now()->subMonth())
              ->groupBy('status')
              ->get();
      

      我得到了 groupBy 状态的结果,每个组中的记录总数为计数,它们的总和为总数

      这两个快照是一个查询结果

      【讨论】:

        猜你喜欢
        • 2013-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-10
        • 1970-01-01
        • 1970-01-01
        • 2019-02-04
        • 2014-09-14
        相关资源
        最近更新 更多