在拉拉维尔(Laravel)上花费时间的最佳方式?

时间:2019-07-03 15:37:34

标签: laravel php-carbon

我有一个名为 transactions 的表,其中有两个与我的问题有关的字段_start_timestamp_和_end_timestamp_。我需要对_end_timestamp_不为null的所有事务之间传递的时间求和。因此,结果必须类似于总交易时间:1小时18分钟

我尝试过使用 Carbon ,但是我不知道如何使用它来汇总表格的所有行。

foreach($timestampStarts as $timestampStart){  
    $time = new Carbon($timestampStart->start_timestamp);
    $shift_end_time =new Carbon($timestampStart->end_timestamp);
    dd($time->diffForHumans($shift_end_time));
}

2 个答案:

答案 0 :(得分:1)

您可以使用MySQL TIMESTAMPDIFF函数来计算差异:

Transaction::whereNotNull('_end_timestamp_')
    ->sum(DB::raw('TIMESTAMPDIFF(SECOND, _start_timestamp_, _end_timestamp_)'));

这将为您提供总计秒数。

答案 1 :(得分:1)

您需要获取以分钟为单位的总差异。添加总差异并检索人类的差异。您可以像下面这样检索:

$diffForHumans = null;
$nowDate = Carbon::now();
$diffInMinutes = 0;

foreach($timestampStarts as $timestampStart){  

    if(!empty($timestampStart->end_timestamp)){ // if the end timestamp is not empty

        $time = new Carbon($timestampStart->start_timestamp);
        $shift_end_time =new Carbon($timestampStart->end_timestamp);

        //Adding difference in minutes
        $diffInMinutes+= $shift_end_time->diffInMinutes($time);
    }
}
$totalDiffForHumans = $now->addMinutes($diffInMinutes)->diffForHumans();