【问题标题】:Property [stock] does not exist on this collection instance此集合实例上不存在属性 [stock]
【发布时间】:2020-11-12 08:14:01
【问题描述】:

在我的 Cart 模型中,我与 Product 模型有关系。在 Product 模型中,我与 Product_attribute 有关系模型。 但我与 Product_attribute 模型没有关系。 在本例中,我编写此代码以访问 Product_attribute 模型。

$getCartDetails = Cart::with('product.product_attribute')->where('id',$id)->first();

这很好。我访问产品和产品属性数据

现在我想计算 product_attribute stock,类似的方法想计算 cart quantity。 如果Product_attribute->stock >= Cart->quantity,我会更新购物车表,否则不会

这就是我写这段代码的原因

   public  function updateCartQuantity($id,$quantity)
   {
       $getCartDetails = Cart::with('product.product_attribute')->where('id',$id)->first();

      if($getCartDetails->product->product_attribute->stock->sum() >= $getCartDetails->quantity->sum()) {

           DB::table('carts')->where('id', $id)->increment('quantity', $quantity);
           return back()->with('success', 'product Quantity in the cart Updated Successfully!');
       }else{
       return back()->with('error', 'Required Product Quantity is not available!');
         }


   }

【问题讨论】:

  • 试试dd($getCartDetails->product->product_attribute->stock) 可能你无法达到库存。
  • 同样的问题。此集合实例上不存在属性 [stock]。
  • 当我使用这个时,我访问产品和产品属性数据` $getCartDetails = Cart::with('product.product_attribute')->where('id',$id)- >第一(); `
  • 尝试$getCartDetails->product->product_attribute()->stock->sum() 而不是$getCartDetails->product->product_attribute->stock->sum() 仍然出现错误,尝试dd($getCartDetails->product->product_attribute)
  • 使用 dd($getCartDetails->product->product_attribute) ,我得到 product_attribute 的所有数据

标签: php database laravel eloquent model


【解决方案1】:

您可以直接查看

$check_qty =    DB::table('product_attribues)->where('product_id',$getCartDetails->product_id)->where('size',$getCartDetails->size)->first();

$check_qty 将根据购物车表 product_id 和 Size 为您提供库存数量。使用 If 条件检查更新的数量和库存数量后。

因为您可以根据 product_id 和 Size 从 product_attribues 表中找到产品库存

【讨论】:

    【解决方案2】:

    查看错误,上面写着property stock doesn't exist on the collection instance.

    只需检查一次关系。正如我从名称中可以理解的那样,该产品可能有多个与之关联的 product_attributes (One to many relation)。这可能是收集错误时属性不存在的原因。而且您正在尝试访问不应该是这种情况的集合上的模型属性。

    编辑:

    $getCartDetails->product->product_attribute->sum('stock') 。这是您的 if 条件所需要的。它将为您获取集合中所有实例的 stock 属性的总和。这是参考https://laravel.com/docs/7.x/collections#method-sum

    【讨论】:

      猜你喜欢
      • 2019-03-23
      • 2020-07-11
      • 2017-05-12
      • 2018-10-12
      • 2021-02-08
      • 2021-12-16
      • 2021-09-14
      相关资源
      最近更新 更多