Problem with eager fetching of statistical query in relation

I have following relation on my class Category (Category has a MANY-MANY relation to Project).

public function relations() {

		return array(

			'projectsCount'=>array(self::STAT, 'Project', '{{project_has_category}}(category_id, project_id)'),		

			'projects' => array(self::MANY_MANY, 'Project', '{{project_has_category}}(category_id, project_id)'),

		        'parent' => array(self::BELONGS_TO, 'Category', 'parent_id'),

      		        'childs' => array(self::HAS_MANY, 'Category', 'parent_id', 'with' => 'projectsCount'),		



Category is an hierarchy. All relations work as expected, ‘projectsCount’ works as well when it is called lazy. When I access the child elements the eager fetch of projectsCount does not work. I can see in my sql trace that they are still lazy loaded:

$model = $this->loadModel($id, 'Category');

foreach ($model->childs as $child) {

  echo $child->projectsCount; // lazy loading logged here!


Do I miss a point in my relations setup?

Eager loading works when you load model using methods of ActiveRecord, not methods of controllers. You should do something like this:

$model = Your_model_class_name::model()->with('Relation_name')->findByPk($id);

foreach ($model->childs as $child) {

  echo $child->projectsCount; 


According to this documentation

you can add eager loading to relations. I am doing the same in my example.

Your example works when I fetch one model, but not for the relation ‘childs’.

Yes, you can do this, but using this option inappropriately may form an infinite relation loop. If you try to load Category object with it’s childs - Category objects, which must be loaded with their childs - it might be an infinite relation loop.

Please have a look at my example in my first post. I am not eager loading childs, but "projectsCount" which is not a hierarchy. There is no problem with an infinite loop.

'childs' => array(self::HAS_MANY, 'Category', 'parent_id', 'with' => 'projectsCount'), 

Your model Category has many Categories, isn’t it?

I just thought here: maybe it use lazy load, because projectsCount is dynamyc value, and framework must return You an actual result.

Yes it has. But Projects-Categories is not an hierarchy. I think there is an limitation in Yii to put statistical queries as eager fetching into relations. Maybe anybody else has a working example or can confirm that is just don’t work. I guess the sql query behind the scene is to complicated to be generated dynamically by the framework.