2017-05-02 88 views
1

有人可以幫助我,查詢Builder也Laravel 5

這我的數據庫SQL查詢 My Table

SELECT supplier, 
MAX(IF(item_name = 'Lemon', price, NULL)) AS Lemon, 
MAX(IF(item_name = 'Apple', price, NULL)) AS Apple, 
MAX(IF(item_name = 'Durian', price, NULL)) AS Durian, 
MAX(IF(item_name = 'Mango', price, NULL)) AS Mango 
FROM offer 
where status = 'open' 
GROUP BY supplier 

如何通過Laravel的QueryBuilder使用此查詢?謝謝...

回答

0
$results = DB::table('offer')->select(DB::raw("supplier, 
    MAX(IF(item_name = 'Lemon', price, NULL)) AS Lemon, 
    MAX(IF(item_name = 'Apple', price, NULL)) AS Apple, 
    MAX(IF(item_name = 'Durian', price, NULL)) AS Durian, 
    MAX(IF(item_name = 'Mango', price, NULL)) AS Mango")) 
->where('status', 'open') 
->groupBy('supplier') 
->get(); 

真的,查詢生成器不是爲複雜的查詢。當他們得到的是複雜的,你可能會發現它更容易只是使用原始聲明:

$results = DB::select("SELECT supplier, 
    MAX(IF(item_name = 'Lemon', price, NULL)) AS Lemon, 
    MAX(IF(item_name = 'Apple', price, NULL)) AS Apple, 
    MAX(IF(item_name = 'Durian', price, NULL)) AS Durian, 
    MAX(IF(item_name = 'Mango', price, NULL)) AS Mango 
FROM offer 
where status = 'open' 
GROUP BY supplier"); 
+0

感謝@Captain超文本,你的回答保存我的天,這完美的工作,,, –

+0

海蘭@CaptainHypertext,非常感謝您以前的答案,我在我的查詢中還有一個問題,我可以使'item_name'或'supplier'列的查詢更具動態性。 在前面的例子中,我有4個'item_name'**(芒果,蘋果,榴蓮,檸檬)**。我真的不知道如何在我的查詢中插入函數。 因爲在實際情況下'item_name'是無限的,它可能是一個或多個 –

+0

@CristalTravel我沒有真正花時間研究你的查詢的邏輯,只是實現。你究竟想用這個查詢做什麼?爲什麼某些項目最終爲NULL而其他人有價格?你的表結構又是什麼? –