Relations In Yii Gridview

I’m trying to use gridview and display data from 2nd table (using foreign key). I can’t figure out how to get it without writing a custom function that will use “store.id” to join and retrieve records from “staff” table.

Table: store (id, name, etc);

store.id = 1

store.name = ‘Store ABC’

store.id = 2

store.name = ‘Store XYZ’

Table: staff (id, store_id, name, etc);

staff.id = 1

staff.store_id = 1 (foreign key)

staff.name = ‘Johnny Walker’

staff.id = 2

staff.store_id = 2 (foreign key)

staff.name = ‘Honey Walker’

Now, I have a protected/views/store/view.php where I want to display staff working at this store only.

So, the URL is basically index.php?r=store/view&id=1 (viewing ‘Store ABC’ details), which should list “Johnny Walker” as the staff working at this store.





$model = Store::model();

$modelStaff = Staff:model();


$this->widget('bootstrap.widgets.TbGridView', array(

	'dataProvider'=>$model->search(),

	'type'=>'striped bordered condensed',

	'columns'=>array(

		array('name'=>'id', 'header'=>'Store ID', 'value'=>$model->id),

		array('name'=>'name', 'header'=>'Store Name', 'value'=>$model->name),

		array('name'=>'staff.name', 'header'=>'Staff Name', 'value'=>$modelStaff->name),

		array('header'=>'View', 'class'=>'bootstrap.widgets.TbButtonColumn',

			'template'=>'{view}',

			'buttons'=>array(

				'view' => array(

					'url'=>'Yii::app()->controller->createUrl("staff/view", array("id"=>$data[id]))',

				),

				'update' => array(

					'url'=>'Yii::app()->controller->createUrl("staff/update", array("id"=>$data[id],"command"=>"update"))',

				),

			),

		),

	),

)); 




I suppose there’s a lot of examples on this site regarding this question.

The common approach is to use eager (or lazy) loading (please read yii guide relational queries topic) and to call relational record data in a form




$model->relation->field_name



Probably, you’ll have something like in your grid view:





        array(

            'name' => 'staff.name',

            'value' => '$data->staff ? $data->staff->name : ""'

        ),