首页 > 解决方案 > 试图获取非对象的属性“产品”(Laravel 8)

问题描述

试图获取非对象的属性“产品”(查看:C:\xampp\htdocs\SSB280\resources\views\frontend\include\menubar.blade.php)

我认为我的产品 Eloquent 不起作用。

带有主要部分的模型 模型表。

class cart extends Model
{
    use HasFactory;

    public $fillable = [
      'user_id',
      'ip_address',
      'order_id',
      'product_id',
      'product_quantity'
    ];

    public function product(){
      return $this->belongsTo(Product::class);
    }

    public static function totalPrice(){
        if ( Auth::check() ) {
            $carts = cart::Where('user_id', Auth::id() )->Where( 'order_id' , Null )->first();
        }
        else{
            $carts = cart::Where('ip_address', request()->ip() )->Where( 'order_id' , Null )->first();
        }

        $total_price = 0;
        foreach( $carts as $cart ){
            if ( !is_null( $cart->product->offer_price ) ) {
                $total_price += $cart->product_quantity * $cart->product->offer_price;
            }
            else{
                $total_price += $cart->product_quantity * $cart->product->reguler_price;
            }
        }

        return $total_price;
    }
}

数据库

 public function up()
        {
            Schema::create('carts', function (Blueprint $table) {
                $table->increments('id');
                $table->integer('user_id')->nullable();
                $table->string('ip_address')->nullable();
                $table->integer('order_id')->nullable();
                $table->integer('product_id')->nullable();
                $table->integer('product_quantity')->nullable();
                $table->timestamps();
            });
   

前端调用

这是我调用方法的地方

<div class="basket-item-count">
  <span class="count">
    {{ App\Models\Frontend\cart::totalItems() }}
  </span>
</div>

<div class="total-price-basket"> 
  <span class="lbl">cart -</span> 
  <span class="total-price"> 
    <span class="sign">$</span>
    <span class="value">{{ App\Models\Frontend\cart::totalPrice() }}BDT</span> 
  </span> 
</div>

标签: phplaravel

解决方案


您通过使用获得单个 Cart 对象

$carts = cart::Where('user_id', Auth::id() )->Where( 'order_id' , Null )->first();

接下来,您将对此进行分析。如果你想要多个 Cart 对象:

$carts = cart::Where('user_id', Auth::id() )->Where( 'order_id' , Null )->get();

为这两个查询更改它。


推荐阅读