問(wèn)題描述
我有一個(gè)包含以下列的消息"表
I have a "messages" table with the following columns
CREATE TABLE `messages` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`fromId` int(11) NOT NULL,
`toId` int(11) NOT NULL,
`message` text NOT NULL,
`status` int(11) NOT NULL,
`device` varchar(100) NOT NULL,
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=57 DEFAULT CHARSET=latin1;
我正在嘗試獲取所有 'toId' = $id 并按 fromId 分組的消息.問(wèn)題是結(jié)果中顯示的消息"是第一個(gè),而不是最新的.我嘗試通過(guò) createdAt 訂購(gòu),但它不起作用.
I'm trying to get all messages where 'toId' = $id and grouping by fromId. The problem is that the "message" shown on the results is the first ones, not the latest ones. I tried ordering by createdAt but it's not working.
如何在查詢和分組結(jié)果之前按createdAt"排序?我想使用 Eloquent 以 laravel 的方式做到這一點(diǎn).
How can I order by "createdAt" prior to querying and grouping the results? I want to do this in the laravel way using Eloquent.
我的查詢:
$chats = Message::with('sender','recipient')
->where('toId',$id)
->orderBy('createdAt')
->groupBy('fromId')
->paginate(10)
推薦答案
我找到了一種方法!基本上,創(chuàng)建一個(gè)子查詢并在之前運(yùn)行它,以便結(jié)果按預(yù)期排序并在其后分組.
I found a way to do that! Basically, creating a subquery and running it before, so that results are ordered as expected and grouped after.
代碼如下:
$sub = Message::orderBy('createdAt','DESC');
$chats = DB::table(DB::raw("({$sub->toSql()}) as sub"))
->where('toId',$id)
->groupBy('fromId')
->get();
這篇關(guān)于Order By before Group By 使用 Eloquent (Laravel)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!