Php 使用条令和符号减少与数据库的连接

Php 使用条令和符号减少与数据库的连接,php,symfony1,doctrine,symfony-1.4,doctrine-1.2,Php,Symfony1,Doctrine,Symfony 1.4,Doctrine 1.2,我获得所有城市并使用计数功能: foreach ($cities as $city) { echo $city->getName() . '|' . CityTable::getInstance()->getCount($city->getId(), a). '|' . CityTable::getInstance()->getCount($city->getId(), b). '|' . CityTable::getInstance()->getCount(

我获得所有城市并使用计数功能:

foreach ($cities as $city) {
echo $city->getName() . '|' . CityTable::getInstance()->getCount($city->getId(), a). '|' . CityTable::getInstance()->getCount($city->getId(), b). '|' . CityTable::getInstance()->getCount($city->getId(), c);
}

public function getCount($id, $num)
   {
       $q = $this->createQuery('u')
           ->where('city_id = ?', $id)
           ->andWhere('num = ?', $num)
           ->execute();

       return count($q);
   }
这工作正常,但这产生了许多连接数据库。foreach中的每次迭代调用三次函数getCount。若我在城市表中有超过1000个城市,那个么我有超过10000个对数据库的查询。
如何减少这种情况?

如果有足够的可用内存,请将整个表加载到一个数组中,并使用simples算法循环它们。如果没有足够的内存,请加载大量数据并在PHP中循环它们


查询数据库是一种简单的方法。您将把db查询减少为几个。

尝试类似以下查询的操作:

       $q = $this->createQuery('u')
           ->select('COUNT(u.id) as count')
           ->where('num = ?', $num)
           ->groupBy('city_id')
           ->execute();