Laravel 7.14显示供用户使用的购物车中没有的产品

问题描述

我要根据购物车表中的产品向每个用户显示产品。如果用户已在购物车中添加了产品,则不应仅在该用户的产品列表中显示该产品。如果该产品在购物车中,我可以显示通知,但是如果该产品已经在购物车表中,则无法隐藏它。

这是我的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();

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...