我有一个问题要解决,我需要计算购物车的总价。
我在购物车中添加了多个商品。他们有价格和数量的枢纽。 像这样:
{
"id": 1,
"user_id": "1",
"status": "closed",
"total_price": "100",
"created_at": "2017-07-22 06:06:17",
"updated_at": "2017-07-22 08:02:04",
"skues": [
{
"id": 1,
"title": "مربعی ۵x2",
"description": "مربعی ۵x2، مربعی ۵x2 است.",
"sku_card_theme": "#2222",
"visible": "hidden",
"price": "50",
"category_id": "2",
"created_at": "2017-07-22 06:50:02",
"updated_at": "2017-07-22 07:16:33",
"pivot": {
"cart_id": "1",
"sku_id": "1",
"feature": "{\"size\": \"big\",\"quantity\": 2}",
"image_path": "images/users5e51d08006fed056b19db7d041d5688f.jpeg",
"id": 1
}
},
{
"id": 1,
"title": "مربعی ۵x2",
"description": "مربعی ۵x2، مربعی ۵x2 است.",
"sku_card_theme": "#2222",
"visible": "hidden",
"price": "50",
"category_id": "2",
"created_at": "2017-07-22 06:50:02",
"updated_at": "2017-07-22 07:16:33",
"pivot": {
"cart_id": "1",
"sku_id": "1",
"feature": "{\"size\": \"big\",\"quantity\": 2}",
"image_path": "images/users/416e9f70dee50547866e9e89696d16e3.jpeg",
"id": 2
}
},
{
"id": 3,
"title": "تقویم دیواری",
"description": "سشیشیش",
"sku_card_theme": "#2222",
"visible": "hidden",
"price": "25",
"category_id": "3",
"created_at": "2017-07-22 07:56:45",
"updated_at": "2017-07-22 07:56:45",
"pivot": {
"cart_id": "1",
"sku_id": "3",
"feature": "{\"size\": \"big\",\"quantity\": 2}",
"image_path": "images/users/273c1f5e3324815a82060931f30ead97.jpeg",
"id": 3
}
},
]
我想在这里总结所有的skues价格并将它们乘以它的支点数量,我尝试了一些方法,如foreach
,laravel collection each
和其他方法......
但我没有答案。
我的代码示例:
$skues->each(function ($item) {
$quantity = json_decode($item->pivot->feature)->quantity;
$price = $item->price;
});
$total_price = $quantity * $price;
它有一个错误,告诉我$quantity
和$price
是未定义的变量。
这是我的foreach方法:
foreach ($cart->skues as $skue) {
$quantity = json_decode($skue->pivot->feature)->quantity;
$total_price = $skue->price * $quantity;
}
$cart->update([
'total_price' => $total_price,
]);
谢谢。
答案 0 :(得分:1)
我最后解决了这个问题:
public function total($cart) {
$cart->update([
'total_price' => NULL,
]);
$cart->skues->each(function ($item) {
$user = auth()->user();
$quantity = json_decode($item->pivot->feature)->quantity;
$price = $item->price;
$total_price = $price * $quantity;
$user->cart->update([
'total_price' => $total_price + $user->cart->total_price,
]);
});
}