【问题标题】:Trying to get property 'pivot' of non-object (Laravel 7 - Accessors)试图获取非对象的属性“pivot”(Laravel 7 - 访问器)
【发布时间】: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


【解决方案1】:

您正在尝试访问枢轴,但它不在集合中。转储 (dd) $this->products,每个集合都缺少枢轴。如果没有 Order 模型,你不能直接这样做。

因此,请尝试调用 $order->products,而不是 $this->products。

顺便说一句,您可以为 ProductOrder 创建另一个模型作为 Pivot。

<?php
namespace AppModels;
use IlluminateDatabaseEloquentRelationsPivot;

class ProductOrder extends Pivot
{
    //
}

【讨论】:

    【解决方案2】:

    幸运的是,我最终找到了解决方案。我改变了这段代码

    foreach ($this->products as $product)
    

    有了这个

    foreach ($this->products()->get() as $product) 
    

    现在它运作良好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-27
      • 2015-09-22
      • 2017-03-20
      • 2014-03-25
      • 2015-01-25
      • 2014-06-23
      相关资源
      最近更新 更多