foreach ($events_id as $id) {
$vis = $visitors->where('event_id', $id);
array_push($men, $vis->where('sex', 'male')->count());
array_push($women, $vis->where('sex', 'female')->count());
array_push($kids, $vis->where('sex', 'kids')->count());
}
I have a collection of visitors and events IDs I want to check how many men - women - kids are in each event
it works but I want something faster
CodePudding user response:
In order to have greater performance it would be better to have integers instead of string to define the gender.
Also if you can modify your database query, it would be interesting to get these data directly through your query.
CodePudding user response:
This can be done direct by your database query but I don`t know why you don't follow it. But In this case we can only make fast by (if-else or swatch) condition.
IF-ELSE condition:
foreach ($events_id as $id) {
$vis = $visitors->where('event_id', $id);
if($vis->sex == 'male'){
array_push($men, $vis->count());
}else if($vis->sex == 'female'){
array_push($women, $vis->count());
}else{
array_push($kids, $vis->count());
}
SWATCH condition:
foreach ($events_id as $id) {
$vis = $visitors->where('event_id', $id);
switch ($vis->sex) {
case 'male':
array_push($men, $vis->count());
break;
case 'female':
array_push($women, $vis->count());
break;
default:
array_push($kids, $vis->count());
break;
}
CodePudding user response:
You can group the result by sex, and then count how many rows are in each group.
SELECT sex, COUNT(sex) as count FROM test.test
WHERE event_id = 0
GROUP BY sex
;
CodePudding user response:
OK TRY THIS:
$male_count = $visitors->whereIn('event_id', $events_id)->where('sex','male')->count();
$female_count = $visitors->whereIn('event_id', $events_id)->where('sex','female')->count();
$kids_count = $visitors->whereIn('event_id', $events_id)->where('sex','kids')->count();
It will work IA.