Laravel 在拉威尔计算时间的最佳方法?

Laravel 在拉威尔计算时间的最佳方法?,laravel,php-carbon,Laravel,Php Carbon,我有一个名为transactions的表,其中有两个与我的问题相关的字段,\u start\u timestamp\u和\u end\u timestamp\u。我需要对所有事务之间经过的时间量求和,其中_end_timestamp_不为空。因此,结果必须类似于事务的总时间:1小时18分钟 我试过使用碳元素,但我不知道如何使用碳元素对表格中的所有行进行求和 foreach($timestampStarts as $timestampStart){ $time = new Carbon

我有一个名为transactions的表,其中有两个与我的问题相关的字段,\u start\u timestamp\u和\u end\u timestamp\u。我需要对所有事务之间经过的时间量求和,其中_end_timestamp_不为空。因此,结果必须类似于事务的总时间:1小时18分钟

我试过使用碳元素,但我不知道如何使用碳元素对表格中的所有行进行求和

foreach($timestampStarts as $timestampStart){  
    $time = new Carbon($timestampStart->start_timestamp);
    $shift_end_time =new Carbon($timestampStart->end_timestamp);
    dd($time->diffForHumans($shift_end_time));
}
您可以使用MySQL函数计算差异:

Transaction::whereNotNull('_end_timestamp_')
    ->sum(DB::raw('TIMESTAMPDIFF(SECOND, _start_timestamp_, _end_timestamp_)'));
这将以秒为单位给出总数。

您可以使用MySQL函数计算差值:

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

这将以秒为单位给出总差值。

您需要以分钟为单位检索总差值。添加总差异并检索人类的差异。您可以按如下方式检索:

$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();

您需要以分钟为单位检索总差异。添加总差异并检索人类的差异。您可以按如下方式检索:

$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();