【问题标题】:how to get data from pivot table inside a many to one relation in laravel 5.6如何在laravel 5.6中的多对一关系中从数据透视表中获取数据
【发布时间】:2019-02-19 19:44:33
【问题描述】:

我有 3 个表名称,例如 "product""user""product_type" 所以在我的情况下 user 和 product_type 具有多对多关系 并且 user 和 product 具有一对多关系关系product 和 product_type 具有一对一的关系

我为用户和产品类型创建了一个数据透视表。在该数据透视表中,我又添加了一列用于描述。所以在产品列表页面中,我需要显示该数据透视表中的描述。

我的代码如下所示:

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

【问题讨论】:

  • 您的意思是“用户和产品类型具有多对多关系”还是您的意思是您也有一个account_type 表?
  • 对不起,我的意思是product_type,实际上是Product::with(['user'=>function($q){$q->with('product_type')}])->with('product_type ')->get();上面的代码提供了数据透视表数据。但我需要使用 product_type_id 进行归档。

标签: laravel laravel-5 laravel-5.6


【解决方案1】:

要从数据透视表中获取额外的字段,您需要在模型的函数中使用 withPivot 像这样:

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

你也可以参考 laravel 文档:

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

【讨论】:

  • 我已经完成了所有工作,并且我正在使用此查询获取数据。实际上 Product::with(['user'=>function($q){$q->with('product_type')}])->with('product_type')->get();上面的代码提供了数据透视表数据。但我需要使用 product_type_id 进行归档。目前我正在从前端刀片管理这些东西
  • 首先使用这种方式获取数据 => Product::with('user.product_type')->get();你能解释一下你到底想要什么吗?
  • 我正在获取用户下的所有产品类型和相关数据透视数据。我需要获取与该产品表相关的一种产品类型。注意:product 和 product_type 有一对一的关系,product 表有 product_type_id
猜你喜欢
  • 2020-07-03
  • 1970-01-01
  • 2018-09-15
  • 1970-01-01
  • 2017-02-12
  • 1970-01-01
  • 2015-02-10
  • 1970-01-01
相关资源
最近更新 更多