如何在Laravel Eloquent中使用Postgresql DISTINCT ON

时间:2019-09-03 19:11:43

标签: sql laravel postgresql eloquent

我正在使用DISTINCT ON从两个连接的表中获取最新的行。就我而言,订户属于许多类别,我需要获取订户所属的最新类别。我已经在原始查询中使用了它,但是我需要使用Eloquent重新创建它。

SELECT DISTINCT ON (subscribers.id) subscribers.*, 
subscriber_categories.* 
FROM subscribers 
LEFT JOIN subscriber_categories
  ON subscribers.id = subscriber_categories.subscriber_id 
ORDER BY subscribers.id, subscriber_categories.created_at DESC;

我尝试了以下操作,但没有用。它正在从两个表中获取所有记录:

Subscribers::
   ->join('subscriber_categories', 'subscribers.id', '=', 'subscriber_categories.subscriber_id')
   ->distinct('subscribers.id')
   ->latest('subscribers.id', subscriber_categories.created_at)
   ->paginate(7);

2 个答案:

答案 0 :(得分:0)

我终于结束了。 (完全放弃DISTINCT ON):

     $subscribers = \DB::table('subscribers AS t1')
        ->leftJoin(\DB::raw('(SELECT * FROM subscriber_categories A WHERE id in (SELECT MAX(id) FROM subscriber_categories group by subscriber_id)) AS t2'), function($join) {
        $join->on('t1.id', '=', 't2.subscriber_id');
            })->select('t1.id', 't1.s_phonenumber', 't1.timesubscribed', 't2.category')->latest('t1.created_at')->paginate(7);

答案 1 :(得分:0)

我遇到了同样的问题,最终写了一个laravel扩展程序来处理它。您可以使用composer安装它,然后就可以使用!

https://packagist.org/packages/datajoe/postgresql-distinct-on

这是您的情况:

Subscribers::
   ->join('subscriber_categories', 'subscribers.id', '=', 'subscriber_categories.subscriber_id')
   ->distinctOn('subscribers.id')
   ->latest('subscribers.id', subscriber_categories.created_at)
   ->paginate(7);