Yii Active Record Relationship with child of child

I have a nested hierarchy, structured something like this:




Parent

 |-Group1

 |  |-Child Type A

 |  \-Child Type B

 |

 \-Group2

    |-Child Type A

    |-Child Type A

    \-Child Type B



Is there a way to define a relationship on the Parent class such that I can access all Child Type A’s linked through it’s Groups?

I know that if I want to get all Child Type A’s I can get the Parent’s related Groups, and for each group get its related Child Type A’s. I’m looking for something simpler, e.g.




$parent = Parent::model()->findByPk(12);

$childrenA = $parent->getRelated('childTypeA');



And I need to know, if it’s possible, how to structure the relationship in the Parent’s model.

Thanks!

You could try:




class Parent extends CActiveRecord

{

   ...

   public function relations()

   {

       return array(

           'groups'=>array(self::HAS_MANY,'Group','parent_id'),

           'children'=>array(self::HAS_MANY,'Child','group_id','through'=>'groups'),

       );

   }

}



See more details here: http://www.yiiframework.com/doc/guide/1.1/en/database.arr#relational-query-with-through

I thought about using "through", but the docs show this feature using a joiner table containing a foreign key to each table we want to join. Specifically, it says

So my Group table would need a fk to the Child. Instead my Child classes have a foreign key to their Group, and the Group has a foreign key to it’s Parent.

Hello,

I am having this exact same issue. I have an AR query that goes multiple levels deep (5 tables) and I want each set of returned relations to be accessible from the returned relations at the level above it. I feel like you should be able to accomplish this with one query. Based on my research, there does not appear to be a way to do this, which is a little disappointing…maybe I missed something. How did you solve this problem?