【问题标题】:Retrieve Pivot table column value in Laravel在 Laravel 中检索数据透视表的列值
【发布时间】:2017-08-03 13:33:35
【问题描述】:

我遇到了一个不应该发生的奇怪问题。

我有一段代码可以检索数据透视表的值

$product = Product::find(296);

dd($product->pivot->aisle);

它应该像我为其他几个项目所做的那样工作。今天突然给我以下错误:

(1/1) ErrorException
Trying to get property of non-object
in ProductController.php (line 42)
at HandleExceptions->handleError(8, 'Trying to get property of non-object', 
'C:\\laragon\\www\\Sales\\app\\Http\\Controllers\\ProductController.php', 
42, array('retailer' => object(Retailer), 'product' => object(Product)))
in ProductController.php (line 42)

在我的产品模型中,我有以下内容:

public function retailers(){

return $this->belongsToMany(Retailer::class)->withPivot('aisle','ifinstock','ifstock','ifticketed','ifonshelf','iflowstock','note','id','created_at','updated_at','stocklevel');

}

在我的零售商模式中,我有:

public function products(){

return $this->belongsToMany(Product::class)->withPivot('aisle','ifinstock','ifstock','ifticketed','ifonshelf','iflowstock','note','id','created_at','updated_at','stocklevel');

}

我就是看不出哪里出错了?

【问题讨论】:

  • 试试 dd($product) 和 dd($product->pivot)。他们中的任何一个都返回null吗?如果是这样,您的问题就从这里开始。
  • 试试dd($product->retailers);
  • 我们可以看看你的产品模型是什么样子的吗?

标签: php laravel model pivot


【解决方案1】:

当您访问 Product::find(296) 时,您不是通过相关模型访问,而是访问 Product 模型本身,因此 Laravel/Eloquent 不会加载任何关系信息,例如数据透视字段,因为这些数据透视字段不是t 为 Product 模型定义,它们是为关系定义的。

如果你这样做:

$retailer = Retailer::with('products')->find(...);

然后访问该模型上的 Products 关系,它应该可以工作:

$product = $retailer->products->first();
var_dump($product->pivot);

总之,产品本身没有任何数据透视字段。枢轴字段用于产品零售商的关系。

【讨论】:

    猜你喜欢
    • 2015-09-02
    • 2021-01-22
    • 2015-01-27
    • 2019-08-21
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 2018-04-10
    • 1970-01-01
    相关资源
    最近更新 更多