2017-05-19 53 views
1

我有一個級別列,需要統計每個列的數量。Laravel 5.3模型 - 計算列 - 哪種方法更快

以下哪個選項更快/更高效,爲什麼?或者可能是我沒有考慮的更快的方法?

$athletes = Athlete::orderBy('level', 'desc')->get(); 

    foreach ($athletes as $a) { 
     switch ($a->level) { 
      case "advanced": 
       $dataAdvanced += 1; 
       break; 
      case "intermediate": 
       $dataIntermediate += 1; 
       break; 
      case "medium": 
       $dataMedium += 1; 
       break; 
      case "beginner": 
       $dataBeginner += 1; 
       break; 
      case "other": 
       $dataOther += 1; 
       break; 
     } 

OR

$dataAdvanced = Athlete::where('level', 'advanced')->count(); 
    $dataIntermediate = Athlete::where('level', 'intermediate')->count(); 
    $dataMedium = Athlete::where('level', 'medium')->count(); 
    $dataBeginner = Athlete::where('level', 'beginner')->count(); 
    $dataOther = Athlete::where('level', 'other')->count(); 
+0

count(*)gorup按等級 – JYoThI

+0

第二個,因爲泛型方法會比你定製的方法更快和優化 –

+0

Athlete :: select('id',\ DB :: raw(「count(level)as TOTAL_COUNT「)) - > GROUPBY( '級別') - >獲得(); – JYoThI

回答

4
If your table name is athletes, note: use DB in controller 
$athletesInfo = DB::table('athletes') 
        ->select('level', DB::raw('count(*) as total')) 
        ->groupBy('level') 
        ->get(); 
2

最好的方法是使用group bycount,如:

$count = Athlete::groupBy('level')->select(DB::raw('count(level) as total'))->get(); 
3

我認爲這是統計計數(水平)和正確的方式按級別分組

Athlete::select('id', \DB::raw("count(level) as total_count"))->groupBy('level')->get();