首页 > 解决方案 > Laravel 异常属性 [product_quantity] 在 Eloquent 构建器实例上不存在

问题描述

我试图在 Laravel 中构建一个电子商务网站,但我收到错误消息“异常属性 [product_quantity] 在 Eloquent 构建器实例上不存在”。当我尝试更新数据库中的产品数量时。

基本上,我想做的是,如果用户尝试添加购物车中已经存在的产品,则数量会增加 1,并且产品总价格会相应更改。为此,我首先检查了数据库中的现有条目

$findProduct = StoreCart::where('product_id', $product->id); 

“StoreCart”是我存储购物车数据的模型名称。然后在查找查询之后我所做的是

if($findProduct) {
            // product is already in DB, set new quantity
            $newQuantity = $findProduct->product_quantity + $getQuantity;
            $newProductTotal = $findProduct->product_price * $newQuantity;
            // update the exsisting product
            $findProduct->update([
               'product_quantity' => $newQuantity,
               'product_total' => $newProductTotal,
            ]);

         } else {
            // create new field and store it in db
            StoreCart::create([
                'user_id' => Auth::id(),
                'product_id' => $product->id,
                'product_name' => $product->name,
                'product_price' => $amount,
                'product_quantity' => $getQuantity,
                'product_total' => $productTotal,
            ]);
        }

当我尝试运行它时,会弹出上述错误,说 [product_quantity] 在 Eloquent 构建器实例上不存在。这有什么问题?

标签: phplaravel

解决方案


您将更$findProduct = StoreCart::where('product_id', $product->id);改为$findProduct = StoreCart::where('product_id', $product->id)->first();. 它会正常工作。根据您的查询输出将是对象的集合。你不能使用更新命令来收集。您可以使用更新评论来反对。


推荐阅读