我正在创建一个功能,该功能允许用户将产品添加到愿望清单中,但是当我单击(“ whishlist”刀片)时出现错误Trying to get property of non-object
,该错误来自此行{{1} }如果我移除了<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'));
}
Wishlist.php
@if (Auth::user()->wishlist->count() )
@foreach($wishlists as $wishlist)
<h2>USD {{$wishlist->product->price }}</h2>
<h4>USD {{$wishlist->product->name }}</h4>
@endforeach
@endif
User.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);
}
}
Product.php
public function wishlist(){
return $this->hasMany(Wishlist::class);
}
答案 0 :(得分:0)
您首先应该更改检查心愿单计数的方式,因为它会执行繁重的查询来恢复所有心愿单然后。并按照@lucasArbex的建议删除$
中的$product
@if ($wishlists->count() )
@foreach($wishlists as $wishlist)
<h2>USD {{$wishlist->product->price }}</h2>
<h4>USD {{$wishlist->product->name }}</h4>
@endforeach
@endif
还可以更改控制器并在用户上使用该关系
public function index()
{
$user = Auth::user();
$wishlists = $user->wishlist()->with('product')
->orderby('id', 'desc')
->paginate(10);
return view('wishlist', compact('user', 'wishlists'));
}
答案 1 :(得分:0)
首先,您应该像这样访问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);
}