Gabesz
Gabesz

Reputation: 303

Yii2 ManyToMany relation - Get Client window's data

I have a small (no, not that small) probleme in my current project. Today I came across with Yii and viaTable but something is not working with it. I think something is wrong with the table linking.

My goal would be to get all the data from the client windows(Ablak) that is connected to a user via felhasznalo2ablak table.

I have 3 tables. Felhasznalo(Users in English), Ablak(Client Window in English) and Felhasznalo2Ablak which is the via table.

Here are the table structures: enter image description here

enter image description here

enter image description here

Felhasznalo(Model):

public function getWindows() {
return $this->hasMany(Ablak::className(), ['id' => 'ablak_id'])-       >viaTable('felhasznalo2ablak',['felhasznalo_id','id']);
}

Ablak(Model):

public function getUsers() {
return $this->hasMany(Felhasznalo::className(), ['id' => 'felhasznalo_id'])->viaTable('felhasznalo2ablak', ['ablak_id' => 'id']);
}

And the query in the controller:

$u = Felhasznalo::findOne(Yii::$app->user->getId());
$allowedWindows = $u->getWindows();
foreach ($allowedWindows as $aw) {
print_r($aw);
}

I want to get the ralational data from Ablak table that blongs to a specific user. It works but not tha way it should. Any ideas guys?

Thank you for your answers!

Gábor

Upvotes: 1

Views: 71

Answers (2)

Gabesz
Gabesz

Reputation: 303

I forget to answer my thread. So the problem was solved by adding forign keys to my database structure and after that i generated the model files with gii.

Upvotes: 0

MacGyer
MacGyer

Reputation: 198

Check the link in your Felhasznalo::getWindows()

public function getWindows() {
    return $this
        ->hasMany(Ablak::className(), ['id' => 'ablak_id'])
        ->viaTable('felhasznalo2ablak', ['felhasznalo_id' => 'id']);
}

Query for all "Windows"

$u = Felhasznalo::findOne(Yii::$app->user->getId());
$allowedWindows = $u->getWindows()->all();

print_r($allowedWindows);

Upvotes: 0

Related Questions