Ahmad Reza Azimi
Ahmad Reza Azimi

Reputation: 582

Laravel eloquent leftJoin ignores orderByDesc when used

Well, I have tried a couple of days trying to find out what is wrong with my code. I have a chat_group and chat_message tables respectively where each group has last_message that belongs to each message sent to a group. When I want fetch all the groups based on the last message sent to a group create_at field, laravel join ignores the orderBy. Here is a piece of my code and DB structure of it:

chat_groups: 
id, 
name, 
last_message_id, 
created_at

chat_messages: 
id: 
text: 
created_at
$groups = ChatGroup::with($relations) 
    ->leftJoin('chat_messages', 'chat_groups.last_message_id', '=', 'chat_messages.id')
    ->withCount('members') 
    ->orderBy('chat_messages.created_at', 'DESC') 
    ->orderBy('chat_groups.created_at', 'DESC') 
    ->get(); 
dd($groups->toArray());

Upvotes: 1

Views: 52

Answers (1)

Ahmad Reza Azimi
Ahmad Reza Azimi

Reputation: 582

I found a solution for my question. I used order by clause on group updated_at field and no need to use leftJoin.

Upvotes: 2

Related Questions