gpt4 book ai didi

php - 对所有商品价格求和并将它们乘以 laravel 中的数据透视表

转载 作者:行者123 更新时间:2023-11-28 23:12:40 28 4
gpt4 key购买 nike

我这里有个问题要解决,我需要计算购物车的总价。

我将多个产品添加到我的购物车。他们有价格和数量的枢轴。像这样:

{
"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 是 undefined variable 。

这是我的 foreach 方法:

foreach ($cart->skues as $skue) {
$quantity = json_decode($skue->pivot->feature)->quantity;
$total_price = $skue->price * $quantity;
}
$cart->update([
'total_price' => $total_price,
]);

谢谢。

最佳答案

我终于修好了:

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,
]);
});
}

关于php - 对所有商品价格求和并将它们乘以 laravel 中的数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45252311/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com