sadek sadek - 2 years ago 44
MySQL Question

How to to return most recent data using group by and order by

I have seen many posts but nothing is wokring. It seems group by always group the oldest one. I want to group the result and pick the most recent one.
Here is my query

Message::whereIn('conversation_id',$msgs)
->orderBy('created_at', 'desc')
->groupBy('conversation_id')
->with(array('last_sender'=>function($query){
$query->select('id','userName','profilePic', 'firstName','lastName');
}))
->get();

Answer Source

Try like this

Message::whereIn('conversation_id',$msgs)
             ->with(array('last_sender'=>function($query){
                    $query->select('id','userName','profilePic', 'firstName','lastName');
              }))
             ->orderBy('conversation_id', 'desc') 
             ->groupBy('conversation_id')
            ->get();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download