Order By before Group By using Eloquent (Laravel)

后端 未结 6 866
无人共我
无人共我 2020-12-03 21:22

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         


        
6条回答
  •  眼角桃花
    2020-12-03 22:01

    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.

    Here is the code:

    $sub = Message::orderBy('createdAt','DESC');
    
    $chats = DB::table(DB::raw("({$sub->toSql()}) as sub"))
        ->where('toId',$id)
        ->groupBy('fromId')
        ->get();
    

提交回复
热议问题