Grab data from Many-to-Many middle table using through

Hello everyone!

I don’t understand some things about the THROUGH feature in a AR relational query.

Let’s consider the following database schema:

USERS

id

name

email

GROUPS

id

name

description

USER_GROUP

userId

groupId

joined - data when the user has joined the group

level - access level the user has in this group

Every user can be in more groups and every group can have more users.

Models available: User, Group and UserGroup.

Relations defined:




class Group extends CActiveRecord

{

   ...

   public function relations()

   {

       return array(

           'rUserGroups'=>array(self::HAS_MANY,'UserGroup','groupId'),

           'rUsers'=>array(self::HAS_MANY,'User','userId','through'=>'UserGroup'),

           // 'oldUsers'=>array(self::MANY_MANY,'User,'USER_GROUP(groupId,userId)),

       );

   }

}






class User extends CActiveRecord

{

   ...

   public function relations()

   {

       return array(

           'rUserGroups'=>array(self::HAS_MANY,'UserGroup','userId'),

           'rGroups'=>array(self::HAS_MANY,'Group','groupId','through'=>'UserGroup'),

           // 'oldGroups'=>array(self::MANY_MANY,'User,'USER_GROUP(userId,groupId)),

       );

   }

}



I want to get all the groups where the user ID is 1 with the level and joined properties from the middle table.




$user = User::model()->with('rGroups')->findByPk(1);

foreach ($user->rGroups as $group) {

    // how do I get "level" and "joined" properties from the USER_GROUP table?

}



Is it possible to get that information in the given code? What are the differences between MANY_TO_MANY and using THROUGH (excepting the situation of the example in the Yii Guide when we get the comments from a group)?

To solve the problem described, I defined two BELONGS_TO relations in the UserGroup model (one for User and one for Group) and I’m using the following code:




$middle = UserGroup::model()->with('rGroups')->findAll('userId=:usr',array(':usr'=>0);



Or using the relation rUserGroup:




$user = User::model()->with('rUserGroup.rGroup')->findByPk(1);



But this has nothing to do with THROUGH parameter.

Can someone, please, clarify what exactly is THROUGH meant to do or explain how to use it do get the information from the middle table?

Thank you!