【问题标题】:Getting daily aggregates/sum sorted by day in Laravel在 Laravel 中按天排序获取每日聚合/总和
【发布时间】:2013-05-26 22:39:23
【问题描述】:

所以在 Laravel 中得到 sum()/count() 真的很容易...... 但是我将如何查看过去一个月,并获得每天的行数?

EG...按创建日期分组。

所以我想返回一个计数,例如 3、2、4、5 这意味着今天创建了 3 行,昨天创建了 2 行,前一天创建了 4 行......等等

如何在 Laravel 中轻松做到这一点? 当我通过 created_at 使用组时,它总是只返回 1。

有人知道怎么做吗?

谢谢

【问题讨论】:

  • 我会说,我已经弄清楚了,在 laravel 中使用原始查询,但只是想知道是否有一种流畅/雄辩的方式来执行此类查询
  • 我在另一篇文章中提供了完全相同的答案:stackoverflow.com/questions/15437854/…

标签: laravel aggregates


【解决方案1】:

我提供了相同的答案on another post。缩短它:

$date = new DateTime('tomorrow -1 month');

// lists() does not accept raw queries,
// so you have to specify the SELECT clause
$days = Object::select(array(
        DB::raw('DATE(`created_at`) as `date`'),
        DB::raw('COUNT(*) as `count`')
    ))
    ->where('created_at', '>', $date)
    ->group_by('date')
    ->order_by('date', 'DESC')
    ->lists('count', 'date');

// Notice lists returns an associative array with its second and
// optional param as the key, and the first param as the value
foreach ($days as $date => $count) {
    print($date . ' - ' . $count);
}

【讨论】:

  • 谢谢。我不得不使用groupBy 和'orderBy' 而不是group_by order_by。你的回答很有帮助。
  • lists 在 Laravel 5.3 中被移除,所以你需要使用 pluck 来代替
猜你喜欢
  • 2018-04-25
  • 1970-01-01
  • 1970-01-01
  • 2012-03-05
  • 1970-01-01
  • 2016-07-10
  • 1970-01-01
  • 2020-12-25
  • 2013-01-22
相关资源
最近更新 更多