2016-05-13 188 views
0

你好朋友我有這個查詢使用sql編輯器運行,但我不知道如何使用laravel.please編寫這個查詢幫助我。如何在laravel中編寫sql查詢

SELECT 
    date, 
    memo, 
(COALESCE(CASE WHEN drcr = 'dr' THEN amount END,0)) total_debits, 
(COALESCE(CASE WHEN drcr = 'cr' THEN amount END,0)) total_credits, 
@b := @b + (COALESCE(CASE WHEN drcr = 'cr' THEN amount END,0)) - (COALESCE(CASE WHEN drcr = 'dr' THEN amount END,0)) balance 
FROM 
(SELECT @b := 0.0) AS dummy 
CROSS JOIN 
tbl_bankrecords 
ORDER BY 
date 

回答

0

原始表達式

有時你可能需要在查詢中使用原始的表達。這些表達式將作爲字符串注入查詢中,因此請小心不要創建任何SQL注入點!要創建原始表達式,你可以使用DB ::原始方法:

$users = DB::table('users') 
    ->select(DB::raw('count(*) as user_count, status')) 
    ->where('status', '<>', 1) 
    ->groupBy('status') 
    ->get(); 

Laravel Doc for Raw Queries

另外:

$someVariable = Input::get("some_variable"); 

$results = DB::select(DB::raw("SELECT * FROM some_table WHERE some_col = :somevariable"), array('somevariable' => $someVariable)); 

http://fideloper.com/laravel-raw-queries

0

你可以試試這個:

Model::select(DB::raw('SELECT 
    date 
,memo 
,(COALESCE(CASE WHEN drcr = 'dr' THEN amount END,0)) total_debits 
,(COALESCE(CASE WHEN drcr = 'cr' THEN amount END,0)) total_credits, 
@b := @b + (COALESCE(CASE WHEN drcr = 'cr' THEN amount END,0)) - (COALESCE(CASE WHEN drcr = 'dr' THEN amount END,0)) balance'))->get(); 
+0

你好亞洲時報Siddharth如何添加此part.will請你ellaborate it.FROM (SELECT @b:= 0.0)作爲虛擬 CROSS JOIN tbl_bankrecords ORDER BY 日期 – akash

+0

只是儘量把所有你所提到的事情'Model :: select(DB :: raw('把你的原始查詢放在這裏')) - > get();'。我不確定,但這應該起作用 – Siddharth