我正在使用簡單的郵資追蹤系統,我試圖用這個查詢做的是帶有最新追蹤狀態名稱的退貨包。如何將這個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::select
DB::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
可能這會有所幫助:http://stackoverflow.com/questions/24823915/how-to-select-from-subquery-using-laravel-query-builder –