I have this schema:
and this relation in model zwz
:
public function getAuftrs() {
return $this->hasMany(\app\models\Auftr::className(), ['id' => 'auftr_id'])
->viaTable('znw', ['zwzx_id' => 'id'])
->viaTable('zwz_expl', ['zwz_id' => 'id'])
;}
in the view of zwz
:
<?= count($model->getAuftrs()->asArray()->all())
I'm getting:
PHP Notice – yii\base\ErrorException
Undefined index: auftr_id
- in C:...\vendor\yiisoft\yii2\db\ActiveRelationTrait.php
And now if I change the two viaTable()
s to:
->via('znws')
and of course define this relation before:
public function getZnws() {
return $this->hasMany(\app\models\Znw::className(), ['zwzx_id' => 'id'])
->viaTable('zwz_expl', ['zwz_id' => 'id'])
;}
then it works.
The problem is, that this latter via()
way is incompatible with yii2-giiant, so I would like to know what is the difference actually between the two, and how could I keep the original viaTable()
way.
for me it seems quite clear that we always have to pick the last ID of the chain and define all other IDs backwards. (however in these docs there is via()
and not viaTable()
and maybe it makes also a difference)
Thanks in advance!
You can not use viaTable()
twice on the same relation. The second call will overwrite the first one. If you want to go over more than a junction table you need via(). You can however define multiple relations, one of them using via()
and the other using viaTable()
.
I have no idea how giiant works, but it may detect a Many-Many relation through the fact that viaTable()
is used. viaTable()
in contrast to via()
skips one table so you do not need an ActiveRecord for the junction table. With via()
you always define direct relations.
About the order of keys in relation definitions, please check the docs at
http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#declaring-relations
[...] the link between the two types of data: specifies the column(s) through which the two types of data are related. The array values are the columns of the primary data (represented by the Active Record class that you are declaring relations), while the array keys are the columns of the related data.
An easy rule to remember this is, as you see in the example above, you write the column that belongs to the related Active Record directly next to it. You see there that customer_id is a property of Order and id is a property of Customer.