简体   繁体   English

使用Doctrine和Symfony减少与数据库的连接

[英]Reduce connect to database with Doctrine and Symfony

I get all City and use function for count: 我得到所有城市并使用功能进行计数:

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

this working ok, but this generated to many connect with database. 这个工作还可以,但是这产生了很多与数据库的连接。 With each iteration in foreach three times called is function getCount. 在foreach中的每次迭代中,函数getCount调用了3次。 If i have in City Table over 1000 Cities then i have over 10000 query to database. 如果我在超过1000个城市的城市表中,那么我对数据库的查询超过10000个。 How can i reduce this? 我该如何减少呢?

Try something like this query: 尝试类似以下查询:

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

If you have enough memory available load the entire table to an array and loop them using a simples algorithm. 如果有足够的可用内存,请将整个表加载到数组中,然后使用简单算法将它们循环。 If you don't have enough memory load chuncks of data and loop them in PHP. 如果您没有足够的内存加载数据块,并在PHP中循环它们。

Querying the DB is the easy (no brainer) way to go. 查询数据库是一种简单的方法(无需费力)。 You'll reduce the db queries to just a few. 您将把数据库查询减少到几个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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