Laravel 1 个查询中的多个计数

Laravel multiple count in 1 Query

我是这个框架的新手,我不知道如何使用 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();

尝试像这样传递闭包:

$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。您正在尝试计算 pallet_condition = 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
}));

我希望这可能有所帮助。

可以,先group by,再count

喜欢:

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

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

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

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