R
R
Ruslan Kasymov2016-04-27 14:30:35
Yii
Ruslan Kasymov, 2016-04-27 14:30:35

How to link across 2 tables in YII2?

there are 3 models:
1. User
2. Organization
3. Terminal
User and Organization are connected through the table l_user_organization
Accordingly, in User the connection is described as follows

public function getRelOrganizations()
{
return $this->hasMany(Organization::className(), ['id' => 'organization_id'])->viaTable('{{%l_user_organization}}', ['user_id' => 'id'])->orderBy(['name_ru'=>SORT_ASC]);
}

And in Organization link to Terminal:
public function getRelTerminals()
{
return $this->hasMany(Terminal::className(), ['organization_id' => 'id'])->orderBy(['name'=>SORT_ASC]);;
}

How now to describe communication from User to Terminal through Organization?
I know that you can access Terminal properties like this:
foreach(User::find()->where(['id'=>1])->one()->relOrganizations AS $organization) {
print_r($organization->relTerminals);
}

But it should be like this:
print_r(User::find()->where(['id'=>1])->one()->relTerminals);

And another related question is how to get the data from the connection as an array, it doesn’t work like that:
User::find()->where(['id'=>1])->one()->getRelOrganizations()->asArray();

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question