【问题标题】:Get grouped and counted entries from the last 7 days in Laravel在 Laravel 中获取过去 7 天的分组和计数条目
【发布时间】:2021-08-08 14:14:25
【问题描述】:

我目前遇到了一个小问题。 我确实想收到日期的结果,按天分组,按天计数。

Day 2021-08-06 | count 12
Day 2021-08-05 | count 130 
Day 2021-08-04 | count 0 
Day 2021-08-03 | count 10 
Day 2021-08-02 | count 80 
Day 2021-08-01 | count 35 
Day 2021-07-31 | count 54


关于如何解决这个问题的任何想法?

我的方法是这样的:

public function getEntries()
{
    $this->where('created_at','>=',Carbon::now()->subDays(7))->get();
}

很高兴得到帮助。

谢谢

【问题讨论】:

    标签: mysql laravel eloquent


    【解决方案1】:

    考虑到这个方法在你的模型里面,你可以使用:

    public function getEntries()
    {
        return DB::table($this->getTable())
            ->selectRaw('count(*) as count, DATE(created_at) day')
            ->groupBy('day')
            ->where('created_at', ">", DB::raw('DATE_SUB(now(), INTERVAL 7 Month)'))
            ->get();
    }
    

    注意:这是在 MySQL 上测试并且运行良好,未在其他数据库上测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多