Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

khanimranm's avatar

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
0 likes
0 replies

Please or to participate in this conversation.