简体   繁体   中英

Very inefficient DQL query in Symfony2 with Doctrine. Need improving

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;

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM