2016-08-19 75 views
0

我不知道的內部SQL中time_diff方法:如何將此查詢轉換爲Laravel Query Builder?

SELECT t1.started_at as chain_break, 
time_to_sec(timediff(t1.started_at,IFNULL(
              (SELECT MAX(t2.ended_at) 
              FROM status_records t2 
              WHERE t2.user_id=189 
              AND t2.started_at< t1.started_at 
             ), t1.started_at 
             ) 
         ) 
       )/3600 AS time_off 
FROM status_records t1 
WHERE t1.user_id=189 
ORDER BY t1.ended_at DESC 
LIMIT 6 

有沒有一個很好的辦法做到這一點,除了把這個查詢在DB::query爲原料SQL?

回答

0

是的,您可以使用selectRaw()將您的子查詢添加爲字段選擇。要創建子查詢,您可以創建另一個查詢生成器。

+0

你會如何使用'selectRaw'達到相同的結果,我的查詢? – mvpasarel

0

嘗試這個

DB::raw("SELECT t1.started_at as chain_break, 
time_to_sec(timediff(t1.started_at,IFNULL(
              (SELECT MAX(t2.ended_at) 
              FROM status_records t2 
              WHERE t2.user_id=189 
              AND t2.started_at< t1.started_at 
             ), t1.started_at 
             ) 
         ) 
       )/3600 AS time_off 
FROM status_records t1 
WHERE t1.user_id=189 
ORDER BY t1.ended_at DESC 
LIMIT 6"); 
+0

大聲笑。謝謝,但我正在尋找一種方法,如果可能的話,在Laravel風格中不使用原始查詢。 – mvpasarel

相關問題