同一桌子上的多个计数(Laravel)

时间:2016-02-20 18:15:35

标签: php mysql laravel

我需要从同一个表中计算几个值。我目前正在重复每个查询,只修改C:\Users\back Office>BCP CLAIMS_CAS_ALL_2004_UPDATED_20101002_HUMANA IN "E:\Health Data\Claims\Claims\Data\CLAIMS_CAS_ALL_2004_UPDATED_20101002_HUMANA.txt" -t, -f "E:\Health Data\Claims\Claims\Format_Files\CLAIMS_CAS_ALL_2004_UPDATED_20101002_HUMANA_Format.txt"-SBACKOFFICE-PC -T 子句。这有效,但很难使用DRY方法。

在我的控制器中,这是我当前调用返回每个所需计数的方法:

where()

我的观点,我这样称呼:

$one = DB::table('stores')->where('store_id', '1')->count();
$two = DB::table('stores')->where('store_id', '2')->count();
$three = DB::table('stores')->where('store_id', '3')->count();
$four = DB::table('stores')->count();
$dutch = DB::table('stores')->where('country', 'Netherlands')->count();
$swedish = DB::table('stores')->where('country', 'Sweden')->count();

return View::make('retailers.index', compact('one','two','three', 'four', 'dutch','swedish'));

这里是否有更合适的方法,然后必须查询一个表的每个计数?任何解决方案将不胜感激。

2 个答案:

答案 0 :(得分:6)

您可以使用以下查询:

$results= DB::table('stores')
             ->select('store_id', DB::raw('count(*) as count'))
             ->groupBy('store_id')
             ->get();

现在在您看来,您可以循环播放它。

@foreach($results as $result)
  {{  $result->store_id  }} 
  {{  $result->count  }}
@endforeach

答案 1 :(得分:0)

你可以按照

的方式运行
SELECT count(*), store_id FROM myTable GROUP BY store_id
相关问题