Order By before Group By using Eloquent (Laravel)

后端 未结 6 865
无人共我
无人共我 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:06

    It should be something along this:

    Message::whereToId($id)->groupBy('fromId')->latest('createdAt')->first();
    

    Update

    After seeing the query that you've added, you probably just need to add a direction to the orderBy function, like this:

    $chats = Message::with('sender','recipient')
        ->select(DB::raw('*, max(createdAt) as createdAt'))
        ->where('toId',$id)
        ->orderBy('createdAt', 'desc')
        ->groupBy('fromId')
        ->paginate(10)
    

提交回复
热议问题