存在多个关系时使用 via() 或 viaTable() 显示属性- YII2

Display attribute using via() or viaTable() when there is multiple relations- YII2

我有模型说,供应商机器,供应商,供应商到零件和零件。

这就是这些 table 相互关联的方式。

在供应商模型中,关系定义如下,以检索部件 table 的 part_name,保持供应商到部件作为连接点 table。

public function getSupplierToParts()
{
    return $this->hasMany(SupplierToPart::className(), ['supplier_id' => 'id']);
}


public function getParts()
{
    return $this->hasMany(Part::className(), ['id' => 'part_id'])->viaTable('supplier_to_part', ['supplier_id' => 'id']);
}

在详细视图中我使用 implode 来显示 part_name

[
    'attribute'=>'Nature of business',
    'value' => implode(\yii\helpers\ArrayHelper::map($model->parts, 'id', 'part_name')),

    ],

我的问题是如何在供应商机器模型而不是供应商模型中显示 part_name?在这种情况下,我认为供应商和供应商到零件变得像两个连接点 tables。我该如何解决?

您可以通过 $model->supplier->parts 通过供应商关系访问零件,假设您与 SupplierMachine 模型中供应商的关系是 supplier。不过,您仍然需要考虑多个部分:

'value' => implode(",", 
    \yii\helpers\ArrayHelper::map($model->supplier->parts, 'id', 'part_name')
),