Relational CGridView

Hey Yiis :)

How can i add relational data in a gridview including the search. So i have a contact which can have one to many locations. One of the locations is used as the main-adress. My plan is to add those fields to the standard gridview (manage) which was generated by the CRUD-generator.


public function relations()


		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

			'locations' => array(self::HAS_MANY, 'Locations', 'contact_id'),

			'persons' => array(self::HAS_MANY, 'Persons', 'contact_id'),



public function search()


		// Warning: Please modify the following code to remove attributes that

		// should not be searched.

		$criteria=new CDbCriteria;



		return new CActiveDataProvider(get_class($this), array(





<?php echo CHtml::link('Advanced Search','#',array('class'=>'search-button')); ?>

<div class="search-form" style="display:none">

<?php $this->renderPartial('_search',array(


)); ?>

</div><!-- search-form -->

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











)); ?>

Thanks in advice…


Hope this can help

You can add array in your view/admin







To displaying search for relation you can check this topicLink

it won’t be ok, becase $data->locations would return an array ! but the CGriveView won’t eval(value) with foreach.

Maybe it could be added for an issue for this enhance.

I have the same problem too.

I have a MANY_MANY relationship and I want to display an array inside a CGridView column,

Does anybody know how to do it without not so much coding?



Then you should just be able to access the relational fields by their name (no table prefix needed).

If you have ambiguous column names then you need to add in a $criteria->alias="x";

But the problem, if I’m not wrong, is that CGridView doesn’t allow an array inside a column, and that happens when you have a HAS_MANY relationship,

Can you put a working example of CGridView with HAS_MANY relatioship?

Thanks for your suggestions.

igna36 ,

Were you able to find any solution for your problem. I also want to implement this but can not find any help :(


I couldn’t find any solution either. Instead I modified CGridView to recognize a ‘|’ character in the first spot of defining a field in CGridView. Usually you provide Name[:Type][:Label] to define a field. I changed it to Name[|Name][:Type][:Label] and then I changed the code to understand the | and to pull the relationship after that pipe and print a comma separated list to the data cell.

So for example, you could just write Parent|Children where parent is a defined member of the parent model and children is a relationship rule in the parent parent model. In each data cell in the Parent column of the GridView it would output Child1, Child 2, Child 3, etc…

It worked for what I needed but then I couldn’t figure out how to extend CGridView to implement this correctly.