A side note: Sometimes if you have a complex SQL query it might not be worth the effort to realize everything with pure AR methods. You can always add a custom method to your active record that performs your SQL. There’s nothing wrong with this approach and it will even be faster since AR doesn’t have to create the SQL for you.
public function countDaytrips() {
$cmd = $this->getDbConnection()->createCommand('<YOUR SQL HERE...>');
return $cmd->queryRow(true);
}
Make sure you call this on the model. Otherwhise dbConnection might not be initialized:
why is het doing the count query for every record from the daytips table?
03:31:22.676012
trace
system.db.CDbCommand
Querying SQL: SELECT COUNT(*) AS `s`, `DaytripTag`.`DaytripId` AS `c0` FROM `Tags` INNER JOIN `DaytripTag` ON (`Tags`.`IdTag`=`DaytripTag`.`TagId`) GROUP BY `DaytripTag`.`DaytripId` HAVING (`DaytripTag`.`DaytripId`=691)
SELECT Tag, COUNT( DaytripTag.DaytripId ) AS `s`, `DaytripTag`.`DaytripId` AS `c0`
FROM `Tags`
INNER JOIN `DaytripTag` ON (`Tags`.`IdTag`=`DaytripTag`.`TagId`)
GROUP BY `DaytripTag`.`DaytripId`, Tag
HAVING (`DaytripTag`.`DaytripId`=511)