You could use a JOIN instead
Nov 3, 2022
4
Level 4
Query with multiple withCounts
Hi,
I am trying to figure out how to get a relationship grouped based on different criteria. I figured out that I could potentially have multiple counts that address different criteria but that doesn't seem to be the best approach.
MyQuery
->when($includeTests, function ($query){
return $query->withCount(['englishTestResults as passed_tests' => function($q){
return $q->where('passed_test', 1);
}]);
})
->when($includeTests, function ($query){
return $query->withCount(['englishTestResults as failed_tests' => function($q){
return $q->where('passed_test', -1);
}]);
})
->when($includeTests, function ($query){
return $query->withCount(['englishTestResults as missed_tests' => function($q){
return $q->where('passed_test', 0);
}]);
})
Is there a better way of running this query?
Thank you in advance!
Please or to participate in this conversation.