Jan 21, 2022
0
Level 2
Query by parent distinct column and order parent results by child column
Purpose
a) The query should return only the latest distinct parent column 'thread_id'.b) The results of the parent should be sorted by child table column read
Code
EmailMessage::whereHas('messageInfos', function($query) {
$query->where('user_id', Auth::id())->where('starred', true);
})
->with(['messageInfos' => function($query) {
$query->where('user_id', Auth::id())->where('starred', true)->orderBy('read');
}])
->latest()
->distinct('thread_id')
->paginate(10);
Output Example
Thread_id ChildTableRead
1 unread
4 unread
2 read
3 read
5 read
6 read
Please or to participate in this conversation.