Php 此集合实例上不存在属性[stock]

Php 此集合实例上不存在属性[stock],php,database,laravel,eloquent,model,Php,Database,Laravel,Eloquent,Model,在我的购物车模型中,我与产品模型相关。在产品模型中,我与产品属性模型相关。 但是我与产品属性模型没有关系。 在本例中,我编写此代码是为了访问Product\u属性Model $getCartDetails = Cart::with('product.product_attribute')->where('id',$id)->first(); 这很好。我访问产品和产品属性数据 现在我想计算产品属性库存,类似的方法是计算购物车数量。 如果产品属性->库存>=购物车->数量,我更新购物车

在我的购物车模型中,我与产品模型相关。在产品模型中,我与产品属性模型相关。 但是我与产品属性模型没有关系。 在本例中,我编写此代码是为了访问
Product\u属性
Model

$getCartDetails = Cart::with('product.product_attribute')->where('id',$id)->first();
这很好。我访问产品产品属性数据

现在我想计算产品属性库存,类似的方法是计算购物车数量。 如果
产品属性->库存>=购物车->数量
,我更新购物车表,否则不更新

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

   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!');
         }


   }

查看错误,它表示集合实例上不存在属性库存。

只需检查一下关系。正如我从名称可以理解的那样,产品可能有多个与之相关联的产品属性(
One-to-many relation
)。这可能是集合错误时属性不存在的原因。您正在尝试访问集合上的模型属性,但实际情况并非如此

编辑:


$getCartDetails->product->product_属性->总和('stock')
。这是您的if条件所需的。它将获得集合所有实例的stock属性的总和。这是您可以直接查看的参考资料

$check_qty =    DB::table('product_attribues)->where('product_id',$getCartDetails->product_id)->where('size',$getCartDetails->size)->first();
$check\u qty将根据carts表产品id和尺寸为您提供库存数量。使用If条件检查更新数量和库存数量后


因为您可以根据产品id和大小从产品属性表中查找产品库存

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