Get one attribute list from table

Hi. I have for example 2 tables.

Lang: id, name, code

User lang: id, userid, langid

In admin lang table im writing a function, which should return all lang codes which user can edit for example.

So i need to select all langids from admin langs table by user id, then i should get lang codes from lang table. How can i do it?

You can do that with relations :

in UserLang, define relation to Lang


'lang' => [self::BELONGS_TO, 'Lang', 'langid']

Then in User model you need relation to UserLang


'userLang' => [self::HAS_MANE, 'UserLang', ['userid' => 'id']

Now:

select user you want to work with:

example:


$user = User::model()->findByPk(1);

// userLanguages will be array of UserLang models (for wanted user)


$userLanguages = $user->userLang;

In each model that is in $userLanguages you can access Lang model trough relation




foreach ($userLanguages as $language) {

   echo $language->lang->code; // to get lang.code

}



1 Like