Laravel 从数据库中区分最新数据
我正在数据库中存储数据。存储的数据如下所示Laravel 从数据库中区分最新数据,laravel,laravel-5,laravel-eloquent,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 ------------------------------
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
在我的控制器中,我试图检索每个月的不同上载版本,但获取每个月的最新插入版本。目前我正在努力
$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
-----------------------------------------
我怎样才能做到这一点
谢谢您应该按分组所有要选择的字段,而不仅仅是一个字段。这篇文章解释了这个问题: 在这种情况下,正确的SQL查询应该是:
SELECT id, upload_month, created_at
FROM uplodaded_file
JOIN (SELECT upload_month, MAX(created_at) created_at
FROM uplodaded_file
GROUP BY upload_month) months
ON upload_month = months.upload_month
AND created_at = months.created_at
这种雄辩的说法有点棘手。在这种情况下,最好使用原始查询 您应该使用latest()方法,而不是orderBy:
UploadedFile::latest()->distinct()->get();
尝试不同的方法;)我没有使用distinct的唯一原因是,它正在执行原始数据库查询,而不是使用ElequentLoquent。据我所知,不幸的是,ElequentLoquent不会进行任何查询,因此不会返回唯一的月份。我将返回所有3个结果。请尝试groupBy('upload_month')和latest。现在它返回两个月,但不是最新的1月1日。此UploadedFile::groupBy('upload_month')->latest()->distinct()->get();