I have a simple CActiveRecord class for a Company that has some CStatRelation’s to some related classes for counting associated records. In Company, I define these relations like this:
public function relations() {
return CMap::mergeArray(parent::relations(), array(
'booksCount' => array(self::STAT, 'Book', 'company_id'),
'usersCount' => array(self::STAT, 'User', 'company_id'),
'reconcilesCount' => array(self::STAT, 'Reconcile', 'company_id'),
));
}
These relations work fine to count the related elements from a Company element, issuing this SQL when I count users, for example:
SELECT `company_id` AS `c`, COUNT(*) AS `s` FROM `user` `t` WHERE (`t`.`company_id`=1) GROUP BY `company_id`
I have a User object for the logged in user that is saved in the CWebUser session with setState/getState. This in turn has a BELONGS_TO relation for the Company the user belongs to, and a common practice in the code is to reference the logged in user’s company via this relation.
My problem, though, is those CStatRelation’s out of the Company record (for example, Yii::app()->user->company->usersCount()). When referenced at subsequent places after the first time, they no longer issue any SQL, they return what must be a cached value (e.g. the same value they returned when they were first called).
I have detailed tracing turned on and can see CActiveRecord is not issuing any SQL when these are called, and I have verified the values being returned are the same values as when they were first called. I have no data caching turned on for the application, and thus no query caching. I verified this by printing Yii::app()->cache at the point of the Stat queries, and it’s null.
I can replace the Stat query with something like:
User::model()->countByAttributes(array('company_id' => Yii::app()->user->company_id))
And it will work perfectly. The proper COUNT(*) SQL query is issued and I get a proper up-to-date count of the related records with no apparent caching of results (as I want). I can also do a count(Yii::app()->user->company->users) and it will also work, although that’s inefficient to retrieve all the data records just to get a count.
So, is there some form of simple caching for CStatRelation returned results? I see descriptions of lazy and eager loading in the documentation. Is this what is biting me? I guess because the Stat query is lazy, it has cached the result and will never return a different result? Is there a way to force it to always reissue SQL to get a fresh result every time?
Thanks for any answer.