【问题标题】:Laravel Exception Property [product_quantity] does not exist on the Eloquent builder instanceLaravel 异常属性 [product_quantity] 在 Eloquent 构建器实例上不存在
【发布时间】:2020-08-02 20:10:09
【问题描述】:

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

基本上,我想做的是,如果用户尝试添加购物车中已经存在的产品,则数量会增加 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 构建器实例上不存在。 这有什么问题?

【问题讨论】:

  • 检查我的答案。

标签: php laravel


【解决方案1】:

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

【讨论】:

  • 当然,就是等定时器用完,不会这么快让我记的
猜你喜欢
  • 2022-01-15
  • 2021-01-06
  • 1970-01-01
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-25
相关资源
最近更新 更多