I'm trying to get unique thread_id with latest order by desc created_time
This is my table sample.
===========================================
= id = thread_id = page_id = created_time =
===========================================
= 1 = 3 = 1 = 1551162660 =
= 2 = 1 = 1 = 1551162661 =
= 3 = 1 = 1 = 1551162662 =
= 4 = 2 = 1 = 1551162663 =
= 5 = 3 = 1 = 1551162664 =
= 6 = 1 = 1 = 1551162665 =
===========================================
This is my code.
DB::table('table_a')->select('thread_id')->orderBy('created_time', 'desc')->where('page_id', $page_id)->distinct()->get();
The problem with my code now is, it skips the latest created_time because of the distinct..
What is the right way to do it?
try using a group by instead of distinct
DB::table('table_a')
->select('thread_id')
->orderBy('created_time', 'desc')
->where('page_id', $page_id)
->groupBy('thread_id')
->get();
You can use the latest() method for that.
DB::table('table_a')->latest('created_time')->distinct()->get();
Edit: If you still have issues you can use the groupBy() method as well.
Official documentation at the Laravel Docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With