Pabloss
(Heros68)
November 10, 2016, 4:38pm
1
Hello I have this relation tables
In controller Tematy I have
return $this->render('view', [
'model' => $this->findModel($id),
])
where findModel is standard protected function.
I would like get access to tables szczegoly, how I can to do?
Tematy Model
/**
* @return \yii\db\ActiveQuery
*/
public function getZamowienias()
{
return $this->hasMany(Zamowienia::className(), ['id_temat' => 'id_temat']);
}
Zamowienia Model
/**
* @return \yii\db\ActiveQuery
*/
public function getSzczegolies()
{
return $this->hasMany(Szczegoly::className(), ['id_zamowienie' => 'id_zamowienie']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getTemat()
{
return $this->hasOne(Tematy::className(), ['id_temat' => 'id_temat']);
}
mikezimin
(Mzimin)
November 10, 2016, 5:36pm
2
I don’t sure that it’s best solution, but it should works:
// Tematy Model
public function getSzczegolies()
{
return Szszegoly::find()->joinWith('zamowienia')->where(['zamowienia.id_temat' => $this->id_temat]);
}
Pabloss
(Heros68)
November 10, 2016, 6:53pm
3
mikezimin:
I don’t sure that it’s best solution, but it should works:
// Tematy Model
public function getSzczegolies()
{
return Szszegoly::find()->joinWith('zamowienia')->where(['zamowienia.id_temat' => $this->id_temat]);
}
I don’t think so, that is correct way.
mikezimin
(Mzimin)
November 10, 2016, 10:32pm
4
Sorry, but I did not quite understand. Did my code help you or not?
Pabloss
(Heros68)
November 11, 2016, 1:08am
5
No, because this creates artificial relations. I used “edgear loading” and it working
In action controller I used with instead standard find model.
return $this->render('view', [
'model' =>Tematy::find()->with('zamowienias')->where(['id_temat'=>$id])->all(),
]);
and in View
<?php foreach ($model as $item): ?>
<li> <?= $item->id_temat ?></li>
<li><?= $item->Nazwa_tematu ?></li>
<ul>
<?php foreach ($item->zamowienias as $zamowienia): ?>
<li><?= $zamowienia->numer_zamowienia ?></li>
<ul>
<?php foreach ($zamowienia->szczegolies as $szczegoly): ?>
<li> <?= $szczegoly->nazwa ?></li>
<?php
endforeach;
?></ul>
<?php endforeach;
?> </ul>
<?php endforeach; ?>
Now I have access to all relations
softark
(Softark)
November 11, 2016, 1:14pm
6
Pabloss:
In action controller I used with instead standard find model.
return $this->render('view', [
'model' =>Tematy::find()->with('zamowienias')->where(['id_temat'=>$id])->all(),
]);
You don’t need to use “all()” here, because there’s only one Tematy with ‘id_temat’ = $id.
return $this->render('view', [
'model' =>Tematy::find()->with('zamowienias')->where(['id_temat'=>$id])->one()
]);
And, further more, you could eager load the nested relations like the following:
return $this->render('view', [
'model' =>Tematy::find()->with('zamowienias.szczegolies')->where(['id_temat'=>$id])->one()
]);
Please check the following section of the guide.
http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#lazy-eager-loading