How to show the other value of record in _view.php

Can someone give an example on how to show the other fields in a record, for example city_id is a foreign key. Instead of showing the value of city_id(FK)in _view.php, it should show the "city name".




<b><?php echo CHtml::encode($data->getAttributeLabel('city_id')); ?>:</b>

<?php echo CHtml::encode($data->city_id); ?>

<br />



Tnx in advance :D




<b><?php echo CHtml::encode($data->getAttributeLabel('city_id')); ?>:</b>

<?php echo CHtml::encode($data->city->name); ?>

<br />



Might be obvious but just in case it’s not, this code should work as long as you have the proper relationship setup in your model file. Making assumptions on your naming conventions and possibly your relationship (BELONGS_TO, HAS_ONE, HAS_MANY), you’d need something like this:




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(

        'city' => array(self::BELONGS_TO, 'Cities', 'city_id'),

    );

}



Thanks a lot @Kochiro, had been searching all over the internet and found it here ! Great work, thanks again !