gpt4 book ai didi

php - 如何根据日期获取价格并将价格作为总价求和?

转载 作者:可可西里 更新时间:2023-11-01 09:00:11 25 4
gpt4 key购买 nike

这是我的代码

 $filter = DB::table('detail_clothes')
->get(['id', 'clothes_detail_date', 'clothes_price'])
->groupBy(function($date){
return Carbon::parse($date->clothes_date)->format('m/Y');
});

$result = [];
$clothes_total_price = 0;
$clothes_date = null;

foreach ($filter as $dn => $dn_value) {
$clothes = Clothes::where('clothes_date', $dn)
->first();

foreach ($dn_value as $k => $dnval) {
$clothes_total_price += $dnval->clothes_price;
$result[$dn]['clothes_total_price'] = $clothes_total_price;
}

$date_temp = date_format(date_create_from_format('Y-m-d', $request->clothes_detail_date),'m/Y');
}

我有两个模型:衣服和细节衣服

Clothes : id, clothes_date, clothes_total_price
DetailClothes : id, clothes_detail_date, clothes_price

示例:当我输入衬衫价格时,它会转到详细的衣服并将其存储在那里,它还会以 clothes_total_price 的形式存储在衣服中

它会按月显示所有记录,但是当我总结时,它没有按我想要的显示,

我想要的例如:首先,如果我两次输入这个月的价格1000,总价应该是2000,如果我两次输入下个月的价格1000,总价应该是2000而不是4000

其次,如果我输入日期示例:2017-08-25,它会存储到两个模型,但特别是对于 CLOTHES 模型,它总是会根据月份和年份将日期更新到最新提交,

example:
at Detail Clothes model it should be like this::
1st submit : clothes_detail_date : 2017-08-25, clothes_price : 1000
2nd submit : clothes_detail_date : 2017-08-01, clothes_price : 2000,

expected result:
at Clothes model it should be like this::
clothes_date : 2017-08-25, clothes_total_price: 3000

注意* Clothes Model 只会显示 1 行记录 month and year ,它永远不会显示 2 record at the same month and year

谁能帮帮我?????

最佳答案

我想你忘了将 $clothes_total_price 重置为零。我还从内部 foreach 移动了 1 行到外部。

foreach ($filter as $dn => $dn_value) {
$clothes_total_price = 0;
$clothes = Clothes::where('clothes_date', $dn)
->first();

foreach ($dn_value as $k => $dnval) {
$clothes_total_price += $dnval->clothes_price;
}
$result[$dn]['clothes_total_price'] = $clothes_total_price;
$date_temp = date_format(date_create_from_format('Y-m-d',
$request->clothes_detail_date),'m/Y');
}

编辑:SQLFiddle 中的附加答案

您按月分组,从该月取最大日期,然后对该月的价格求和:

INSERT INTO 
Clothes (clothes_date, clothes_total_price)
SELECT * FROM (
SELECT
MAX(clothes_detail_date) new_clothes_date
,SUM(clothes_price) new_clothes_total_price
FROM DetailClothes
GROUP BY DATE_FORMAT(clothes_detail_date,'%Y%m')
) newTable
ON DUPLICATE KEY UPDATE
clothes_date=newTable.new_clothes_date
,clothes_total_price=newTable.new_clothes_total_price
;

关于php - 如何根据日期获取价格并将价格作为总价求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46640959/

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