Reputation: 33
I'm building a chart with information taken from a database that contains city names. Currently, I'm counting how many times each distinct city name comes up in the database.
The way I've done this is:
I find the city names in the database and pushed the result to $result
.
I then proceed with a while loop, that creates a query builder on each iteration, I then run a query for finding the amount of times that the city comes up and push the result to $count
, then push the value of $count
into the $result
that contains its corresponding city name.
At the moment there are 30 cities in the database, this means that I'm running 30 queries each time the page is loaded and that amount is just going to get higher, can anyone point me in the right direction of how to reduce this process, I'm fairly sure it's possible to find the count of each city at the same time as finding $result
but I'm not sure how and I'm not finding anything online.
$qb = $entityManager->createQueryBuilder();
$qb->select('accident.city')->distinct();
$qb->from('VisDatasetBundle:Accident','accident');
$result = $qb->getQuery()->getResult();
$i = 0;
$qb->delete();
while($i < count($result)){
$qb = $entityManager->createQueryBuilder();
$qb->select('count(accident.city)');
$qb->from('VisDatasetBundle:Accident', 'accident');
$qb->where('accident.city = \'' . $result[$i]['city'] . '\'');
$count = $qb->getQuery()->getResult();
$result[$i]['count'] = $count[0]['1'];
$qb->delete();
$i++;
}
return $result;
Upvotes: 1
Views: 51
Reputation: 9782
This should help you ... use groupBy to group the cities then count the instances.
$qb = $entityManager->createQueryBuilder();
$qb->select('accident.city','count(accident.city)')
->from('VisDatasetBundle:Accident','accident')
->groupBy('accident.city');
Upvotes: 1