Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel orderby query with distinct

Tags:

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?

like image 897
Freddie Avatar asked Feb 26 '19 06:02

Freddie


2 Answers

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();
like image 200
Shobi Avatar answered Oct 05 '22 23:10

Shobi


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.

like image 22
Kerel Avatar answered Oct 06 '22 00:10

Kerel