Laravel Orderby查询与不同

时间:2019-02-26 06:56:50

标签: php laravel sql-order-by distinct

我正在尝试按desc created_time的最新顺序获取唯一的thread_id

这是我的餐桌样品。

===========================================
= 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   =
===========================================

这是我的代码。

DB::table('table_a')->select('thread_id')->orderBy('created_time', 'desc')->where('page_id', $page_id)->distinct()->get();

我的代码现在的问题是,由于与众不同,它跳过了最新的created_time。

正确的方法是什么?

2 个答案:

答案 0 :(得分:1)

尝试使用分组方式而不是distinct

DB::table('table_a')
 ->select('thread_id')
 ->orderBy('created_time', 'desc')
 ->where('page_id', $page_id)
 ->groupBy('thread_id')
 ->get();

答案 1 :(得分:1)

您可以为此使用Latest()方法。

DB::table('table_a')->latest('created_time')->distinct()->get();

编辑:如果仍然有问题,您也可以使用groupBy()方法。

Official documentation at the Laravel Docs.