Laravel 1查询中的多个计数

时间:2018-10-26 05:37:54

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

该框架是我的新手,我不知道如何使用db :: raw count和别名对其进行优化,并使用@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();

4 个答案:

答案 0 :(得分:0)

尝试像这样传递闭包:

$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();

答案 1 :(得分:0)

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

情况1。您正在尝试计算货盘条件= 1;

的项目

情况2。您正在尝试计算货盘条件= 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
}));

我希望这会有所帮助。

答案 2 :(得分:0)

您可以首先group by,然后获得count

赞:

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

答案 3 :(得分:0)

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

 $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 Status 的结果,并且在每组中的记录总数作为计数以及它们的总和作为总数

sample of one group

enter image description here

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

相关问题