I have a tables Users
, Conversations
, Messages
, all I need is to get list of conversation where last message belong to specific user only in Laravel Eloquent
Users
id | name |
---|---|
1 | User 1 |
2 | User 2 |
Conversation
id | name |
---|---|
1 | Conversation 1 |
2 | Conversation 2 |
3 | Conversation 3 |
Messages
id | user_id | conversation_id | text | created_at |
---|---|---|---|---|
1 | 1 | 1 | hi | 2022-23-12 19:33:00 |
1 | 2 | 1 | hi | 2022-23-12 19:34:00 |
1 | 2 | 2 | hello | 2022-23-12 19:35:00 |
1 | 1 | 2 | hello | 2022-23-12 19:36:00 |
what I need, if I want to get conversation list of User (ID: 1) it needs to show me only Conversation 1(ID:1), because User 1 (ID: 1) wrote last message on this conversation and etc...
thanks for answer
I try a lot of thing like leftJoin and where condition and also try whereExists not working
CodePudding user response:
If your relations are set up correctly, you can do:
$user = User::find(1);
$user->messages()
->latest()
->first()
->conversation;