Tuesday 11 February 2014

How to set the country, state relationship in Yii




My Country table:
================
id
name


My state table:
===============
id
country_id
name



Here i need to refer the country from state using the country_id relationship

So first i need to generate a Relationship in my State Model like below


public function relations()
{

return array(
'country'=>array(self::BELONGS_TO, 'Country', 'country_id'),
);

}

Country here is the country model
country_id is the reference key in state table to refer the country table


Ok so in CGrid view use the below format

'country.name',


===========================================================================

And if we need filtering for countries in state admin?

Just use the compare setup like below

public function search()
{
// @todo Please modify the following code to remove attributes that should not be searched.

$criteria=new CDbCriteria;

$criteria->compare('id',$this->id);
$criteria->compare('name',$this->name);
$criteria->with = array('country');
$criteria->compare('country.id',$this->country_id, true);

return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}


And in your Cgridview area have it like below


array(
'name'=>'country_id',
'header'=>'Country',
'value'=>'$data->country->name',
'filter'=>CHtml::listData(Country::model()->findall(),'id','name' ),
),

No comments:

Post a Comment