php - 将产品添加到愿望清单 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);
}
解决方案
首先,您应该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);
}
推荐阅读
- javascript - 显示时如何将动画应用于元素?
- javascript - 如何以角度形式实现我想通过子组件动态呈现表单控件的功能?
- javascript - 通过数组索引将对象从数据传递到 Vue.js 中的组件
- javascript - 为什么 (null==undefined) 在 JavaScript 中为真?
- objective-c - 如何在录制iOS时进入后台时执行strava的操作
- javascript - Angular 表单发送空数据
- hive - 如何让 Beeline 命令行界面识别向上箭头键按下
- elasticsearch - 搜索结果的 ElasticSearch 阈值
- javascript - Webpack 中 Webpack-Manifest-Plugin 的用途
- c - fgets() 和 scanf("%[^\n]") 都被跳过