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 “” to join and retrieve records from “staff” table.

Table: store (id, name, etc); = 1 = ‘Store ABC’ = 2 = ‘Store XYZ’

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

staff.store_id = 1 (foreign key) = ‘Johnny Walker’ = 2

staff.store_id = 2 (foreign key) = ‘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(


	'type'=>'striped bordered condensed',


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

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

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

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



				'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


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


            'name' => '',

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