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

标签 php mysql laravel

这是我的代码

 $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/

相关文章:

laravel - 在 Laravel 的 Blade 模板中显示格式化属性

php - 比较简单的 Preg_match_all 导致 502 Bad Gateway

php - Ajax/jQuery 到 PHP 又回来了?

PHPUnit:失败时跳过所有测试

mysql - 使用 ISNULL 和 ALIAS 时 'on clause' 中的未知列

mysql - 根据另一个表中的计数列出一个表中的详细信息

php - Eloquent updateOrCreate 总是创建

php - 你如何在 PHP 中使用内存缓存

PHP MySQLi 在插入时将文件重命名为行 ID

php - 命令 "make:seeder"未在 Lumen 5.2 中定义