mysqlyiiyii-cactiverecord

CGridView with relational tables


I have two relational tables: location & location_types.

Location

  - location_id
  - location_name
  - location_type_id

Location_types

 - location_type_id
 - location_type

And I made a view with the CGridView widget, everything works fine, even the filer field is working, except in the location_type column is only displaying the location_type_id.

The CGridView widget in the view:

$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => array(
    array('name' => 'location', 'header' => 'Location'),
    array(           
        'name' => 'location_type_id', 
        'header' => 'Location Type'
        ),
),

The relation part from the Location_types model

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(
                'locationlocationtype_rel' => array(self::BELONGS_TO, 'Locations', 'location_type_id'),
    );
}

So: how can I replace the location_type_id with location_type?


Solution

  •  array(           
            'name' => 'location_type_id', 
            'header' => 'Location Type'
            'value' => '$data->locationlocationtype_rel->location_type' // use relations property here
            ),