Searching A Gridview Comprised Of Related Tables

In Larry Ullman’s tutorial ‘Learning the Yii Framework’ he creates a small app with two tables Employee and Department.

On the ‘Manage Employee’ page there is a grid view where an admin user can filter Employee records. However there is only a ‘Department Id’ column, and so I added a ‘Department Name’ column for readability, as shown in the following code:


$this->widget('zii.widgets.grid.CGridView', array(







		'', //(I ADDED THIS LINE HERE.......!!!)













)); ?>

This works fine because of ‘relations’ method in the employee model

public function relations()


		return array(

			'department' => array(self::BELONGS_TO, 'Department', 'departmentId'),



However this column is neither sortable nor filterable in the same way that the other columns are.

Any clue how I would go about this?

And what is the general way of doing this sort of thing when tables are in relation like this?

Do I create an sql view in the database joining both tables and then run Gii on that… or is there a neater way of adapting the code I already have?

Dear Friend

There is an excellent wiki article.

Just go through it.

Searching and sorting by related model in CGridView

Thank you seenivasan. This explained perfectly what I needed to know. :)

I am trying out the yii framework and was banging my head against the wall about this particular issue. Nice to know this forum is responsive and accurate. Gives me faith to keep persevering with Yii

Here’s another one for reference as well:

Displaying, sorting and filtering HasMany & ManyMany relations in CGridView


I should have properly searched the wiki; now I know it’s there I guess I have a lot of homework to do. Thanks again.

I just released a behavior to help with this: Related Search Behavior