dongmo20030416 2011-09-05 20:10
浏览 51
已采纳

使用Doctrine和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. If i have in City Table over 1000 Cities then i have over 10000 query to database. How can i reduce this?

  • 写回答

2条回答 默认 最新

  • douchensi8625 2011-09-06 05:02
    关注

    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.

    Querying the DB is the easy (no brainer) way to go. You'll reduce the db queries to just a few.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?