2017-02-14 151 views
2

我想根據表中的其他列計算Laravel中的列,但由於MySQL不允許,我無法對它們執行WHERE操作。如何在Laravel雄辯中計算列的WHERE子句?

我想我需要一個子查詢。我能夠在MySQL中這樣做:

SELECT * FROM(
SELECT 
@inactive_percentage:=((UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(APP_UPDATE_DATE)))/(UNIX_TIMESTAMP(DEL_TASK_DUE_DATE) - UNIX_TIMESTAMP(APP_UPDATE_DATE)) * 100 AS inactive_percentage, 
IF(@inactive_percentage <= 33, "low", IF(@inactive_percentage >= 33 && @inactive_percentage <= 66, "normal", "high")) AS inactive 

FROM APP_CACHE_VIEW 
) as foo WHERE `inactive`='low' 

但我不知道如何在Laravel中做同樣的事情。我在網上有一些參考資料,但它們對我毫無意義。我如何將它翻譯成雄辯碼?

回答

0

使用DB :: raw作爲您的自定義子查詢。

$datas = DB::table(DB::raw('SELECT 
@inactive_percentage:=((UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(APP_UPDATE_DATE)))/(UNIX_TIMESTAMP(DEL_TASK_DUE_DATE) - UNIX_TIMESTAMP(APP_UPDATE_DATE)) * 100 AS inactive_percentage, 
IF(@inactive_percentage <= 33, "low", IF(@inactive_percentage >= 33 && @inactive_percentage <= 66, "normal", "high")) AS inactive 
FROM APP_CACHE_VIEW as foo'))->where('active','low')->get(); 

then 
foreach($datas as $data){ 
    //Your data processing/formatting 
} 
+0

原始內部的SELECT語句需要用'()'包裝,並且它仍然說'語法錯誤或訪問衝突:1248每個派生表都必須有自己的別名' – Rohan