Yii, get value from another table with foreign key

I am new to the yii framework, so I could help with some help. Suppose I have a table in my database with users, 1 of the profile fields is nationality. In another table, I got a lot of nationalities like this:

id Nationality short 1 Germany DE 2 France FR 3 Netherlands NL 

etc. about 60 + nationalities. For custom purposes, user nationality is associated with this table, for example:

 id username nationality 1 user 1 

which means the nationality of the user 1 = Germany. but how can i choose germany from nationality table when im in profile?

I hope I understand, ask again :)

Greetings, Stefan.

+4
source share
2 answers

You need model classes for both tables, for example

 class Profile extends CActiveRecord { ... } class Nationality extends CActiveRecord { ... } 

Then in the Profile model, you need to relate to Nationality :

 public function relations() { return array( 'nationality' => array(self::BELONGS_TO, 'Nationality', 'nationality'), ), } 

The name of the relationship 'nationality' is how you relate to the related model, for example:

 $profile = Profile::model()->findByPk($id); echo $profile->nationality->short; 

Resources

+10
source

Ottomans, for what relationship: see the relational model :

 'nationality' => array(self::BELONGS_TO, 'Nationality', 'nationality') 

Amd in your view, if you use CDetailView , you can refer to a nationality by its relationship name and call its attributes using dot:

 nationality.short 

read CDetailView docs for more examples

+2
source

Source: https://habr.com/ru/post/1386531/


All Articles