通过group by和Laravel获取最新行 [英] Get most recent row with group by and Laravel

查看:84
本文介绍了通过group by和Laravel获取最新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使有这样的多个问题,我也无法通过查询查询返回带有分组依据的最新日期的行.

Even though there are multiple questions like this I can't get my query to return the row with the most recent date with a group by.

我有下表.

| message_id | from | to | created_at | status
----------------------------------------------
|    1       |   1  |  2 | 2017-04-06 |   1
|    2       |   1  |  2 | 2017-04-07 |   0
|    3       |   3  |  4 | 2017-04-06 |   1
|    4       |   3  |  4 | 2017-04-07 |   0
----------------------------------------------

我正在尝试获取具有最新日期的行.

and I'm tryin to get the rows with most recent date.

| message_id | from | to | created_at | status
----------------------------------------------
|    2       |   1  |  2 | 2017-04-07 |   0
|    4       |   3  |  4 | 2017-04-07 |   0

当前,该查询返回具有最近日期的行.

Currently this query returns the rows with the last recent date.

$messages = Message::where('to', Auth::id())
                    ->groupBy('from')
                    ->orderBy('created_at', 'DESC')
                    ->paginate(10);

推荐答案

问题是结果集将首先被分组,然后被排序.您可以使用嵌套选择来获取所需的内容.

The problem is that the result set will be first grouped then ordered. You can use nested select to get what you want.

SQL查询:

SELECT t.* FROM (SELECT * FROM messages ORDER BY created_at DESC) t GROUP BY t.from

使用Laravel:

$messages = Message::select(DB::raw('t.*'))
            ->from(DB::raw('(SELECT * FROM messages ORDER BY created_at DESC) t'))
            ->groupBy('t.from')
            ->get();

您只需要添加您的where()子句.

You just need to add your where() clauses.

这篇关于通过group by和Laravel获取最新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆