Clear Understanding About Relations In Yii

Can anyone plz explain me the relations with real examples. I read many topics about this and it is really confusing for me.

Thanks in advance

Hi palraj,

          	see supppose there is are two tables, [i][b]country(country_id, country_name) and employee(id,name, country_id),[/b][/i] 

Now ech emplyee belongs to some country, the country_id field is common in both table,

if u wnat to know the country name of some employee then how u will get in Yii?

–>> Firest u will create model related to both table(Employee and Country)

–> Then, in Employee model(suppose related to employee table), there is relation function by default generated by Gii for you, U will suppose set the relation name like.country as below…,

In Employee model…




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



so, now country is a relation between then, below how u will access the country name of an employee…




$record = Employee::model()->with('country')->findByPk('<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/biggrin.gif' class='bbc_emoticon' alt=':D' />=:id',array(':id'=>$id));

echo $record->country_name;



I think this will help u,

Hi Mannu,

Thanks a lot for your clear explanation. Your post gives me a basic understanding about relations in YII. I will start to read more about this.

Can you please give me some complex relations examples?

Thanks

hello palraj now am explaining the HAS_MANY relationship. consider the scenario that you are working in an inventory project in that project you have two tables for billing management say bill and item in the bill table it contains general information such as bill_id, total, discount, tax, grand_total and in item table it contains item_id, name, qty, bill_id where bill_id refers to bill table’s bill_id. in that case a bill has many items in it so we are separated this into separate table. and we can get this items information through HAS_MANY relationship in Bill model. and in Item model the relationship is BELONGS_TO relationship with Bill model