Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort main query by subquery

I need to list all the conversations of a user, sorting by the last received message (same as the conversations of whatsApp).

In this way it orders correctly, but duplicates the conversations.

I tried to use distinct() to solve this, but it ended up asking to put the messages.created_at inside the select, then it duplicates the results again.

Chat::where('chats.from_id', $user_id)
        ->join('messages', 'chats.id', '=', 'messages.chat_id')
        ->select('chats.*')
        ->orderBy('messages.created_at', 'desc')
        ->get();
like image 496
Diego Vieira Avatar asked Oct 20 '25 20:10

Diego Vieira


1 Answers

Use this:

Chat::where('chats.from_id', $user_id)
    ->join('messages', 'chats.id', '=', 'messages.chat_id')
    ->select('chats.*', DB::raw('max(messages.created_at) latest_message'))
    ->groupBy('chats.id')
    ->orderBy('latest_message', 'desc')
    ->get();

You can also use relationships, e.g.:

Chat::where('chats.from_id', $user_id)
    ->withCount(['messages as latest_message' => function($query) {
        $query->select(DB::raw('max(created_at)'));
    }])
    ->orderByDesc('latest_message')
    ->get();
like image 106
Jonas Staudenmeir Avatar answered Oct 24 '25 19:10

Jonas Staudenmeir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!