【发布时间】:2019-10-14 15:22:10
【问题描述】:
我正在创建一个允许用户在愿望清单中添加产品的功能,但是当我单击(愿望清单刀片)时出现错误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
Wishlist.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);
}
【问题讨论】:
-
删除
$...$wishlist->product->price。
标签: php laravel laravel-5 eloquent