如何将这个sql查询写入laravel 5流畅的查询构建器?

时间:2016-02-20 09:06:52

标签: mysql laravel laravel-5.2 laravel-query-builder

我正在研究简单的邮资跟踪系统,我正在尝试使用此查询返回包含最新跟踪状态名称的包。

我使用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

1 个答案:

答案 0 :(得分:1)

DB :: select返回一个数组而不是一个集合/对象,因此不能直接在其上调用分页。如果您需要对查询进行分页,请使用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();

希望有所帮助