【发布时间】:2022-10-08 21:30:09
【问题描述】:
我在我的项目中使用了 Laravel 7。该项目在名为“orders”和“products”的两个表之间具有多对多关系。以下是我的“订单”模型代码。
public function products()
{
return $this->belongsToMany('App\Product')
->withPivot('quantity', 'unit_discount', 'unit_price');
}
public function getTotalGrossPriceAttribute()
{
$totalGrossPrice = 0;
foreach ($this->products as $product) {
$totalGrossPrice += ($product->pivot->quantity *
($product->pivot->unit_discount + $product->pivot->unit_price));
}
return $totalGrossPrice;
}
但不幸的是,它带来了这个错误“试图获取非对象的属性'pivot'”!如果能告诉我我的代码到底出了什么问题,我将不胜感激。
【问题讨论】:
-
尝试 - >pivot() 而不是 - >pivot
标签: laravel pivot-table laravel-7 accessor