如何将此 sql 查询写入 laravel 5 流畅的查询生成器?

How to write this sql query into laravel 5 fluent query builder?

我正在开发简单的邮资跟踪系统,我试图用这个查询做的是 return 具有最新跟踪状态名称的包裹。

我用 DB::select 来执行这个查询,它工作得很好,但我不能用 paginate 来执行它。

DB::select(DB::raw('SELECT p.*, 
       (SELECT status.name 
        FROM   status 
               INNER JOIN tracking 
                       ON tracking.status_id = status.id 
        WHERE  tracking.package_id = p.id 
        ORDER  BY tracking.id DESC 
        LIMIT  1) AS status_name 
FROM   packages AS p 
WHERE  p.is_deleted = 0 
ORDER  BY p.id DESC'));

所以有什么方法可以让我用它来使用 paginate..?或者我可以使用 DB::table 而不是 DB::select

这是我的表格

packages table:
+----+-------------+------------+
| id | tracking_no | account_no |
+----+-------------+------------+
|  3 |      852369 |      90905 |
+----+-------------+------------+

tracking table:
+----+------------+-----------+
| id | package_id | status_id |
+----+------------+-----------+
|  3 |          3 |         1 |
|  9 |          3 |         2 |
| 10 |          3 |         3 |
+----+------------+-----------+

status table:
+----+------------------+
| id |       name       |
+----+------------------+
|  1 | Ready            |
|  2 | Out for delivery |
|  3 | Delivered        |
+----+------------------+

这是我的查询

SELECT p.*, 
       (SELECT status.name 
        FROM   status 
               INNER JOIN tracking 
                       ON tracking.status_id = status.id 
        WHERE  tracking.package_id = p.id 
        ORDER  BY tracking.id DESC 
        LIMIT  1) AS status_name 
FROM   packages AS p 
WHERE  p.is_deleted = 0 
ORDER  BY p.id DESC

DB::select returns 不是数组 collection/object 所以不能直接调用分页。如果您的查询需要分页,请使用 DB::table 或 eloquent。你可以试试这个。

 DB::table('packages')
      ->select(['packages.*',DB::raw('(SELECT status.name 
           FROM   status 
           INNER JOIN tracking 
           ON tracking.status_id = status.id 
           WHERE  tracking.package_id = packages.id 
           ORDER  BY tracking.id DESC 
           LIMIT  1) as status_name')])
      ->where('packages.is_deleted','=',0)
      ->orderBy('packages.id','desc')->paginate();

希望对您有所帮助