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?
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.