与数据库不同的最新数据

时间:2017-01-30 14:44:29

标签: laravel laravel-5 laravel-eloquent

我正在将数据存储在我的数据库中。存储的数据如下所示

id  | upload_month | created_at
-----------------------------------------
1   | January      | 2017-01-30 13:22:39
-----------------------------------------
2   | Febuary      | 2017-01-30 13:23:42
-----------------------------------------
3   | January      | 2017-01-30 13:25:33

在我的控制器中,我正在尝试检索不同的upload_month,但每个都获得最新的插入版本。目前我正在尝试

$uploadedFile = UploadedFile::groupBy('upload_month')->orderBy('created_at', 'desc')->get();

问题是这会返回以下内容

id  | upload_month | created_at
-----------------------------------------
1   | January      | 2017-01-30 13:22:39
-----------------------------------------
2   | Febuary      | 2017-01-30 13:23:42
-----------------------------------------

因此,对于1月份的记录,它正在提供旧版本。如果我将其更改为->orderBy('created_at', 'asc'),则会返回相同的记录,但是二月是第一行。

在本质上,我所追求的是这个

id  | upload_month | created_at
-----------------------------------------
1   | January      | 2017-01-30 13:25:33
-----------------------------------------
2   | Febuary      | 2017-01-30 13:23:42
-----------------------------------------

我如何实现这一目标?

由于

3 个答案:

答案 0 :(得分:2)

您应该router.route('/add/:url(*)') 要选择的所有字段,不只有一个。本文解释了该问题:https://www.psce.com/blog/2012/05/15/mysql-mistakes-do-you-use-group-by-correctly/

在这种情况下,正确的SQL查询是:

GROUP BY

这个雄辩的版本有点棘手。在这种情况下,最好使用原始查询。

答案 1 :(得分:1)

您应该使用latest()方法而不是orderBy:

$this->loadComponent('Auth', [
        'authorize' => ['Controller'],
        'storage' => ['className' => 'Session', 'key' => 'Auth.Admin'],
         /* ... */
    ]
);

答案 2 :(得分:1)

我遇到了这个问题并通过这种方式解决了。

UploadedFile::select(DB::raw('upload_month, MAX(created_at) as latest_date'))
->groupBy('upload_month')->orderBy('latest_date', 'desc')->get()
相关问题