问题描述
我要根据购物车表中的产品向每个用户显示产品。如果用户已在购物车中添加了产品,则不应仅在该用户的产品列表中显示该产品。如果该产品在购物车中,我可以显示通知,但是如果该产品已经在购物车表中,则无法隐藏它。
这是我的CartsController:
// Check if item exists
$status = Cart::where('user_id',Auth::user()->id)
->where('product_id',$product_id)->first();
if(isset($status->user_id) && isset($request->product_id)){
session()->flash('warning','You already have this item in cart.');
}
我的购物车表中有user_id和product_id。
如何创建购物车表是否已登录user_id和product_id以隐藏产品的检查?
购物车用户关系:
public function user()
{
return $this->belongsTo(User::class);
}
购物车关系:
public function product()
{
return $this->belongsTo(Product::class);
}
解决方法
//Get IDs for products in cart
$productsInCart = Cart::where('user_id',auth()->user()->id)->pluck('product_id')->toArray();
//Get products not in cart
$productsToShow = Product::whereNotIn('id',$productsInCart)->get();