2016-01-20 58 views
0

下面我粘貼了mysql查詢。請幫助我將此查詢轉換爲laravel 5.如何將mysql查詢轉換爲laravel 5?

select 
t.username, 
sum(case when t.status_id = 1 then t.count else 0 end) as status_1, 
sum(case when t.status_id = 0 then t.count else 0 end) as status_0, 
sum(case when t.status_id = 0 and t.status_desc = 2 then t.count else 0 end) 
     as status_0_2, 
sum(case when t.status_id = 0 and t.status_desc = 3 then t.count else 0 end) 
as status_0_3 
from (
select username, status_id, status_desc, count(status_desc) as count 
from log 
group by username, status_id, status_desc 
) as t 
group by t.username; 
+0

爲什麼要將其轉換爲Laravel的方案?只需創建一個視圖,並與口才...... –

+0

我的項目在laravel我的工作進行查詢,和我在MySQL的解決方案,但我沒有對自己在使用laravel情況下任何想法。這就是爲什麼。\ –

+0

好吧,那麼有道理。轉換它祝你好運!我相信給出的答案可以滿足你的需求,你試過了嗎? –

回答

1

以下是如何編寫它(您可能想要測試此代碼,但是)。

一些需要注意的有關使用DB::raw

DB ::原始()是用來做未通過查詢器解析任何進一步的任意SQL命令。因此,他們可以通過SQL注入創建一個攻擊向量。記住

就這樣,我使用他們在這裏假設你不傳遞任何用戶輸入他們爲了執行計數和有條件的查詢參數。

請隨便看看Laravel Documentation上查詢生成器是如何工作的更多信息。大多數人不會總是善待爲你寫你的疑問。

// compile the sql for the select query 
$selectRaw = \DB::table('log')->select([ 
    'username', 
    'status_id', 
    'status_desc', 
    \DB::raw('count(status_desc) as count') 
])->groupBy('username', 'status_id', 'status_desc')->toSql(); 

// create and execute the full query 
$result = \DB::table(\DB::raw("({$selectRaw}) as t"))->select([ 
    't.username', 
    \DB::raw('sum(case when t.status_id = 1 then t.count else 0 end) as status_1'), 
    \DB::raw('sum(case when t.status_id = 0 then t.count else 0 end) as status_0'), 
    \DB::raw('sum(case when t.status_id = 0 and t.status_desc = 2 then t.count else 0 end) as status_0_2'), 
    \DB::raw('sum(case when t.status_id = 0 and t.status_desc = 3 then t.count else 0 end) as status_0_3'), 
])->groupBy('t.username')->get();