Reputation: 111
I have "chat" table in my db .
Where recipient_user_id
is who getting message and sender
is sender .
Each message in chat is new row in this table .
Problem .
When User opens his profile I wanna display
----------------------------------------------------
|User_name_who_talked_with| last_message| time_sent |
|----------------------------------------------------
|..... |
|...... |
|---------------------------------------------------|
My query is
$chat = Chat::where('sender_user_id',$user->user_id)
->groupBy('recipient_user_id')
->orderBy('updated_at','desc')->get();
But is displays not last_message . Displays first message .
Upvotes: 2
Views: 1950
Reputation: 520
@Dilip answer will also work to fetch unique data but to get latest (unique) messages, use following query:
$messages = Message::where('receiver_id',$request->user_id)
->orderBy('created_at', 'DESC')
->get()
->unique('sender_id')
->values()
->all();
Upvotes: 1
Reputation: 15296
Chat::where('sender_user_id',$user->user_id)
->orderBy('updated_at', 'desc')
->get()
->unique('recipient_user_id');
The query will return all messages ordered by updated_at
and the unique
method will reduce it down to one message for each recipient_user_id
.
$chats = Chat::select(DB::raw('*, max(updated_at) as updatedAt'))
->where('sender_user_id',$user->user_id)
->orderBy('updatedAt', 'desc')
->groupBy('recipient_user_id')
->get();
Upvotes: 7