如何在laravel 5.6中从多对一关系中获取数据透视表中的数据

问题描述 投票:0回答:1

我有3个表名,如"product""user""product_type",所以在我的情况下,用户和product_type有很多关系,用户和产品有一对多的关系,产品和product_type有一对一的关系。

我为user和product_type创建了一个数据透视表。在该数据透视表中,我添加了一列用于描述。因此,在产品列表页面中,我需要显示该数据透视表中的描述。

我的代码看起来像这样:

Product::with('user)->with('product_type')->get();
laravel laravel-5 laravel-5.6
1个回答
0
投票

要从数据透视表中获取额外的字段,您需要在模型的功能中使用withPivot,如下所示:

public function product_type() {
      return $this->belongsToMany('App\Product','product_type','product_id','user_id')->withPivot('column1', 'column2');
    }

你也可以参考laravel docs:

https://laravel.com/docs/5.7/eloquent-relationships

© www.soinside.com 2019 - 2024. All rights reserved.