首页 > 解决方案 > 将产品添加到愿望清单 laravel

问题描述

我正在创建一个允许用户在愿望清单中添加产品的功能,但是当我单击(愿望清单刀片)时出现错误,如果我删除它Trying to get property of non-object,错误来自这一行,它显示没有价格我该如何解决这个?<h4>USD {{$wishlist->product->price }}</h4>$product

愿望清单控制器

public function index()
{
     $user = Auth::user();
     $wishlists = Wishlist::where("user_id", "=", $user->id)->orderby('id', 'desc')->paginate(10);
     return view('wishlist', compact('user', 'wishlists'));
}

@if (Auth::user()->wishlist->count() )
@foreach($wishlists as $wishlist)

<h2>USD {{$wishlist->product->price }}</h2>
<h4>USD {{$wishlist->product->name }}</h4>

@endforeach
@endif

愿望清单.php

class Wishlist extends Model
{
protected $table = "wishlist";
protected $fillable=['product_id','user_id'];

public function user(){
   return $this->belongsTo(User::class);
}

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

用户.php

 public function wishlist(){
    return $this->hasMany(Wishlist::class);
 }

产品.php

 public function wishlist(){
    return $this->hasMany(Wishlist::class);
 }

标签: phplaravellaravel-5eloquent

解决方案


首先,您应该product像这样访问关系(删除$):

$wishlist->product->price

product其次,您应该使用::with()查询构建器急切地加载愿望清单:

public function index()
{
     $user = Auth::user();

     $wishlists = Wishlist::with('product')
          ->where('user_id', $user->id)
          ->orderby('id', 'desc')
          ->paginate(10);

     return view('wishlist', compact('user', 'wishlists'));
}

另外,如果我是正确的,那么您的产品关系是错误的。

你的愿望清单应该有很多产品(而不是相反)。

在您的前端,您将需要遍历所有愿望清单的产品:

@foreach($wishlist->products as $product)
    {{ $product->price }}
@endforeach

Wishlist将班级中的关系更改为hasMany

public function products()
{
   return $this->hasMany(Product::class);
}

推荐阅读