How to get informations from a join table

Hi, my first post here !

I’ve got an User model, a Group model and a GroupUser model with group_id and user_id (join table). Relations are declared as MANY_MANY in both User and Group models.

Details here:

User class




public function relations()

	{

		return array(

			'group_user'=>array(self::MANY_MANY, 'Group','group_user(group_id, user_id)'),

		);

	}



Group class




	public function relations()

	{

		return array(

			'group_user'=>array(self::MANY_MANY, 'User','group_user(group_id, user_id)'),

		);

	}




Saying:

I want to display in a group action view all the users belongings to that group.

How to achieve that ???

Many thanks




$group=Group::model()->with('group_user')->findByPk($yourGroupID);


// to output in view, do something like

foreach($group->group_user as $user)

  echo $user->name;

Group class




public function relations()

{

    return array(

        'users' => array(self::MANY_MANY, 'User','group_user(group_id, user_id)'),

    );

}







$group = Group::model()->findByPk($groupId);

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

    var_dump($user);

}



Hi mbi & Mike,

many thanks,

I’ll try your solutions, and keep you in touch.

Luc

it works !

AR association are easy in fact :)

Thanks again