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)

http://www.yiiframework.com/tutorial/image?type=guide&version=1.1&lang=en&file=has_many_through.png

In case the link doesn’t work:


Group

-----

id PK

name


Role

-----

user_id PK, FK2

group_id PK, FK1

name


User

-----

id PK

username

password

email


Comment

------

id PK

user_id FK1

content

You want to view a group so you go to the link www.website.com/group/view/1 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);

		

	$this->render('view',array(

		'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(

	'data'=>$model,

	'attributes'=>array(

		'id',

		'name',

)); ?>


<h1>Users</h1>

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

	'dataProvider' => $userDataProvider,

	'itemView' => '/user/_view,

)); ?>



/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.....

</div>



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

etc......



Thanks!

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',