How To Retrieve And Display Extra Field From Associative Table?

I’m a noob to Yii but I’ll do my best to explain the problem. Imagine a database and model design like this:

Go to the link to see the schema:

(can’t use the image extension, probably because I am new)

In case the link doesn’t work:



id PK




user_id PK, FK2

group_id PK, FK1




id PK






id PK

user_id FK1


You want to view a group so you go to the link which activates the actionView() method in GroupController. In the view there also should be a list of the users who are a member of that group so in the actionView() method of GroupController the code would look something like this:

public function actionView($id)


	$model = $this->loadModel($id);

	$users = $model->users;

	$userDataProvider = new CArrayDataProvider($users);



		'model' => $model,

		'userDataProvider' => $userDataProvider,



In the Group model the relations() method would look like this:

'roles'=>array(self::HAS_MANY, 'Role', 'group_id'),

'users' => array(self::HAS_MANY, 'User', array('user_id' => 'id'), 'through' => 'roles'),

and then finally in the View the code would be like this:

<?php $this->widget('zii.widgets.CDetailView', array(





)); ?>


<?php $this->widget('zii.widgets.CListView', array(

	'dataProvider' => $userDataProvider,

	'itemView' => '/user/_view,

)); ?>


<div class="view">

	<b><?php echo CHtml::encode($data->getAttributeLabel('id')); ?>:</b>

	<?php echo CHtml::link(CHtml::encode($data->id), array('view', 'id'=>$data->id)); ?>

	<br />

	<b><?php echo CHtml::encode($data->getAttributeLabel('name')); ?>:</b>

	<?php echo CHtml::encode($data->name); ?>

	<br />

        //I want to display the users role here.....


My Question: In the list of users how would I also display their corresponding field ‘name’ from the table ‘role’?

For example: In the view I want the list of users to be displayed like this:

id        name          role

1         User1         owner

2         User2         member



I have the same problem and I couldn’t find any solution :(

You can use the relationship. They are many so you have to set which one you want,

This will get the first one.


array('header' => 'Name',

'value' => '$model->user[0]->name',