Order By before Group By using Eloquent (Laravel)

后端 未结 6 855
无人共我
无人共我 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();
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-03 22:07

    This work for me: (you can remove the order by createdAt in case createAt increase along with id)

    DB::select(DB::raw('select * from (select * from messages group by fromId desc) m order by m.createdAt'));
    
    0 讨论(0)
  • 2020-12-03 22:11

    I just needed to do something similar with a messages model. What worked for me was applying the unique method on the returned eloquent collection.

    Model::where('toId', $id)
        ->orderBy('createdAt', 'desc')
        ->get()
        ->unique('fromId');
    

    The query will return all messages ordered by createdAt and the unique method will reduce it down to one message for each fromId. This is obviously not as performant as using the database directly, but in my case I have further restrictions on the query.

    Also, there are many more useful methods for working with these collections: https://laravel.com/docs/5.2/collections#available-methods

    0 讨论(0)
  • 2020-12-03 22:22

    Try this query :

    $chats = Message::with('sender','recipient')
    ->where('toId',$id)
    ->whereRaw('id IN (select MAX(id) FROM messages GROUP BY fromId)')
    ->orderBy('createdAt','desc')
    ->paginate(10)
    
    0 讨论(0)
  • 2020-12-03 22:25
     $data = MCCAddMilkEntry::where('coming_from','=','society')
            ->whereRaw('id = (select max(`id`) from mcc_add_milk_entry)')->get();
    
    0 讨论(0)
提交回复
热议问题