Get most recent row with group by and Laravel

前端 未结 5 1760
悲哀的现实
悲哀的现实 2020-12-18 14:34

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.

I have the following table..

5条回答
  •  粉色の甜心
    2020-12-18 15:13

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

    SQL Query:

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

    With Laravel:

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

    You just need to add your where() clauses.

提交回复
热议问题