【问题标题】:Reduce connect to database with Doctrine and Symfony使用 Doctrine 和 Symfony 减少对数据库的连接
【发布时间】:2011-11-10 20:34:41
【问题描述】:

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

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 中的每次迭代调用了 3 次函数 getCount。如果我在城市表中有超过 1000 个城市,那么我对数据库有超过 10000 个查询。 我怎样才能减少这种情况?

【问题讨论】:

    标签: php symfony1 doctrine symfony-1.4 doctrine-1.2


    【解决方案1】:

    试试这样的查询:

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

    【讨论】:

      【解决方案2】:

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

      查询数据库是一种简单(无需费脑)的方法。您可以将数据库查询减少到几个。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多