2016-02-20 75 views
0

我正在使用簡單的郵資追蹤系統,我試圖用這個查詢做的是帶有最新追蹤狀態名稱的退貨包。如何將這個SQL查詢寫入laravel 5流利的查詢生成器?

我用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::selectDB::table代替

這裏是我的表

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 
+0

可能這會有所幫助:http://stackoverflow.com/questions/24823915/how-to-select-from-subquery-using-laravel-query-builder –

回答

1

DB :: select返回數組不是集合/對象所以不能直接調用分頁。如果你需要分頁查詢,請使用DB :: table或雄辯。你可以試試這個。

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(); 

希望它可以幫助

+0

喜歡工作一個魅力,謝謝先生^ _^ –

+0

歡迎Darwish – oseintow