按日期排序进行分组

时间:2014-02-05 15:34:19

标签: mysql sql laravel

我收到按日期订购的用户的最新未读邮件:

$messages = Message::whereReceiver(Auth::user()->id)->whereRead(0)->orderBy('sent', 'desc')->get();

,输出为:

Array
(
    [0] => Array
        (
            [id] => 17
            [suggest_id] => 5
            [content] => How are you?
            [receiver] => 1
            [sent] => 2014-02-05 18:50:37
            [read] => 0
        )

    [1] => Array
        (
            [id] => 16
            [suggest_id] => 5
            [content] => Hi
            [receiver] => 1
            [sent] => 2014-02-05 18:09:15
            [read] => 0
        )
)

但当我做groupBy时,结果将不再下降:

$messages = Message::whereReceiver(Auth::user()->id)->whereRead(0)->orderBy('sent', 'desc')->groupBy('suggest_id')->get();

输出

Array
(
    [0] => Array
        (
            [id] => 16
            [suggest_id] => 5
            [content] => Hi
            [receiver] => 1
            [sent] => 2014-02-05 18:09:15
            [read] => 0
        )
)

但是我希望日期为2014-02-05 18:50:37的消息是输出!

2 个答案:

答案 0 :(得分:0)

这可能是另一种选择(如果您只想获得一条/第一条消息)

Message::whereReceiver(Auth::user()->id)
       ->whereRead(0)
       ->orderBy('sent', 'desc')
       ->take(1) // Just get the top/first one from the set, ordered by desc
       ->get();

如果您想获取所有未读消息,那么它(您已经拥有)

Message::whereReceiver(Auth::user()->id)
       ->whereRead(0)
       ->orderBy('sent', 'desc')
       ->get();

答案 1 :(得分:0)

这是SQL的“问题”。

将此查询转换为SQL查询将是:

select * from messages where read = 0 group by suggest_id order by sent desc

默认情况下,mysql会对行进行分组并获得第一个显示的行。要在mysql中显示组中的最后一行:

select * from ( select * from messages where read = 0 order by sent desc ) as messages group by suggested_id

你可以用Eloquent做到这一点,但不是一个好主意,如果你想改进这个,你可以创建一个视图并设置一个事件来更新每个小时这个视图。

要使用eloquent执行上述查询,您可以执行以下操作:

$results = DB::select('select * from ( select * from messages where read = ? order by sent desc ) as messages group by suggested_id', array(1));