Php Laravel5.7:使用视图中返回的模型获取当月的sum()

Php Laravel5.7:使用视图中返回的模型获取当月的sum(),php,mysql,laravel,Php,Mysql,Laravel,我试图获取当前月份字段“花费的时间”的总和,因此当它是下个月时,它将重新开始。我的模型中当前有: public function transactions() { return Transaction::groupBy('created_at') ->selectRaw('sum(time_spent) as sum') ->pluck('sum'); } 然后在我的刀片视图中,我使用以下命令调用: $info->transactions()->

我试图获取当前月份字段“花费的时间”的总和,因此当它是下个月时,它将重新开始。我的模型中当前有:

 public function transactions()
{
    return Transaction::groupBy('created_at')
    ->selectRaw('sum(time_spent) as sum')
    ->pluck('sum');
}
然后在我的刀片视图中,我使用以下命令调用:

$info->transactions()->sum()

这确实返回了从数据库花费的时间总和,但它不关心创建的时间,我假设它没有使用它,我创建的时间列是timestamp()

创建的时间是从一年到第二年的时间戳(YYYY-MM-DD HH:MM:ss)。
如果您试图按某个月求和,则需要确定进行此操作的年份和月份。
所以,用这个来代替:

public function transactions($year, $month)
{
    return Transaction::selectRaw('sum(time_spent) as sum')
        ->where('YEAR(created_at)', '=', $year)
        ->where('MONTH(created_at)', '=', $month)
        ->pluck('sum');
}

$year = 2018; //change in application
$month = 11; //change in application
$info->transactions($year, $month)->sum();

您需要使用
whereMonth
whereYear
方法按当前月份和年份过滤交易。之后,您可以使用数据库的
sum
方法对所花费的所有时间进行求和

您的方法应如下所示:

public function transactions($year, $month)
{
    return Transaction::whereYear('created_at', $year)
        ->whereMonth('created_at', $month)
        ->sum('time_spent');
}
$month = date('m');
$year = date('Y');

$transactions = $info->transactions($month, $year);
这将运行与此类似的查询(取决于您使用的数据库):

要获取当前月份,应调用如下方法:

public function transactions($year, $month)
{
    return Transaction::whereYear('created_at', $year)
        ->whereMonth('created_at', $month)
        ->sum('time_spent');
}
$month = date('m');
$year = date('Y');

$transactions = $info->transactions($month, $year);

你到底需要什么?所有交易的
时间\或仅某个月的时间?当月的所有交易,因此,如果我现在查看我的页面,它将仅给出11月的所有交易的总和,即12月。它将仅显示12月的总和,等等。。在表中,我有一些信息和列time_花费的时间,以及一个timestamp列created_at。