我有一個級別列,需要統計每個列的數量。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();
count(*)gorup按等級 – JYoThI
第二個,因爲泛型方法會比你定製的方法更快和優化 –
Athlete :: select('id',\ DB :: raw(「count(level)as TOTAL_COUNT「)) - > GROUPBY( '級別') - >獲得(); – JYoThI