如何从Laravel 5.6中的许多到一个关系中从枢轴表中获取数据



我有3个表名,例如 "product""user""product_type",因此在我的情况下用户和product_type具有许多与之的关系用户和用户和产品对于许多关系产品和product_type具有一对一关系

我为用户和product_type创建一个枢轴表。在该枢轴表中,我添加了另外一列以进行描述。因此,在产品清单页面中,我需要从该枢轴表显示描述。

我的代码看起来像这样:

Product::with('user)->with('product_type')->get();

要从枢轴表获取额外的字段,您需要在此类模型的功能中使用with pivot:

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

您也可以将Laravel Docs转介:

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

相关内容