【发布时间】: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