使用Laravel查询数据和分组

Tec*_*Kat 5 php database laravel eloquent

我运行一个存储图像的网站,用户获得热链接.

我希望能够在包含上传图像数据的表中查询过去7天内创建的记录,created_at仅提取列,并将数据编译成数组,类似于为博客制作存档列表.

我希望结果呈现如下:

[
    'Sunday' => 5,
    'Monday' => 45,
    'Tuesday' => 452,
    ...
]
Run Code Online (Sandbox Code Playgroud)

其中每个数字代表每天创建的记录数.只要我能输出这样的数组,我就可以轻松处理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>';
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Jef*_*ert 8

我假设一周中每天旁边的数字代表当天记录数量,您要查询的整个数据集仅在过去7天内查询.

这里的想法是选择在同一天创建的项目计数(完全忽略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);
Run Code Online (Sandbox Code Playgroud)

另请注意,我认为这是一个"滚动"周,如果今天恰好是星期四,那么数据集中的第一个日期将是上周四.它不会在最近的星期天开始,如果这是你需要的.如果是,您可以将-where()条件更改为以下内容:

...
->where('created_at', '>=', Carbon\Carbon::parse('last sunday'))
...
Run Code Online (Sandbox Code Playgroud)