使用 Laravel 查询数据并按天分组

Querying Data and Grouping by Day with Laravel

我运行一个存储图片的网站,用户得到一个热链接。

我想查询上传图片数据的table最近7天的记录,只提取created_at列,将数据编译成数组,类似于为博客制作存档列表。

我希望结果显示如下:

[
    'Sunday' => 5,
    'Monday' => 45,
    'Tuesday' => 452,
    ...
]

其中每个数字代表每天创建的记录数。只要能输出这样的数组,Javascript这边就可以轻松搞定了。

有人有什么建议吗?

编辑

这是我目前试过的代码:

<?php

class Admin
{
    public function getCreatedAtAttribute($value)
    {
        $this->attributes['created_at'] = Carbon::createFromFormat('Y-m-d H:i:s', $value);
    }
    public static function uploadsGraph()
    {
        $date       = \Carbon\Carbon::now();
        $uploads    = Upload::select('created_at')->where('created_at', '>=', \Carbon\Carbon::now()->subWeek())->get();

        foreach($uploads as $date)
        {
            echo $date->created_at . '<br>';
        }
    }
}

编辑 2

这是我试过的另一个版本,但效果不佳。

class Admin
{
    public static function uploadsGraph()
    {
        $date           = \Carbon\Carbon::now();
        $uploadsByDay   = DB::table('uploads')
                            ->select(DB::raw('
                                YEAR(created_at) year,
                                MONTH(created_at) month,
                                MONTHNAME(created_at) month_name
                            '))
                            ->groupBy('year')
                            ->groupBy('month')
                            ->orderBy('year', 'desc')
                            ->orderBy('month', 'desc')
                            ->get();
        dd($uploadsByDay);
    }
}

我假设一周中每一天旁边的数字代表当天记录的数量,您要查询的整个数据集范围仅超过最近 7 天。

这里的想法是 select 同一天创建的项目数(完全忽略 created_at 列的时间戳部分),因此我们可以使用 DB::rawselect() 调用中聚合在特定日期创建的所有条目,然后将该数据集限制为仅在上周创建的条目。这样的事情应该有效:

$data = Upload::select([
      // This aggregates the data and makes available a 'count' attribute
      DB::raw('count(id) as `count`'), 
      // This throws away the timestamp portion of the date
      DB::raw('DATE(created_at) as day')
    // Group these records according to that day
    ])->groupBy('day')
    // And restrict these results to only those created in the last week
    ->where('created_at', '>=', Carbon\Carbon::now()->subWeeks(1))
    ->get()
;

$output = [];
foreach($data as $entry) {
    $output[$entry->day] = $entry->count;
}

print_r($output);

另请注意,我假设这是 'rolling' 周,如果 今天 恰好是 星期四 ,那么数据集中的第一个日期将是之前的星期四。它不会在最近的 星期日 开始,如果您需要的话。如果是,您可以将 -where() 条件更改为如下内容:

...
->where('created_at', '>=', Carbon\Carbon::parse('last sunday'))
...
DB::table("clicks")

->select("id" ,DB::raw("(COUNT(*)) as total_click"))

    ->orderBy('created_at')

    ->groupBy(DB::raw("MONTH(created_at)"))

    ->get();