douzong5835 2017-04-12 22:35 采纳率: 100%
浏览 419
已采纳

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

I have for models say, supplier-machine, supplier, supplier-to-part and parts. enter image description here

This is how these tables are related to each other.

In Supplier model the relation is defined as below to retrieve part_name of Part table keeping supplier-to-part as junction 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']);
}

In Detail view I use implode to display part_name

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

    ],

My question is how do I display part_name in supplier-machine model instead of supplier model?? In this case I think supplier and supplier-to-part becomes like a two junction tables. How do I solve this?

  • 写回答

1条回答 默认 最新

  • drv54591 2017-04-13 03:11
    关注

    You can access the parts through the supplier relation via $model->supplier->parts, assuming your relation to Supplier in your SupplierMachine model is supplier. You still have to account for the multiple parts though:

    'value' => implode(",", 
        \yii\helpers\ArrayHelper::map($model->supplier->parts, 'id', 'part_name')
    ),
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部