使用Laravel查询数据和分组

时间:2015-04-20 16:12:18

标签: php database laravel eloquent

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

我希望能够在包含上传图像数据的表中查询过去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);
    }
}

2 个答案:

答案 0 :(得分:8)

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

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

$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);

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

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

答案 1 :(得分:4)

DB::table("clicks")

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

    ->orderBy('created_at')

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

    ->get();