2013-08-17 117 views
5

我正在使用這樣的laravel查詢生成器。Laravel查詢生成器不綁定值

$col1 = Input::get('col1',''); 
$col2 = Input::get('col2',''); 
$result = DB::table('table1') 
     ->select('id', 'col1', 'col2', 'col3') 
     ->whereRaw("col1 like '%?%'", [$col1]) 
     ->whereRaw("col2 like '%?%'", [$col2]) 
     ->orderBy($orderBy, $orderType) //orderBy=col1, ordeyType=ASC 
     ->skip($ofset)->take($limit) //$ofser=0, $limit=10 
     ->get(); 

我什麼也沒有。如果我使用toSql()函數。我得到這樣的SQL像這樣

select `id`, `col1`, `col2`, `col3` 
from `table1` where col1 like '%?%' and col2 like '%?%' 
order by `col1` ASC limit 10 offset 0 

問號不應該在那裏。它必須用值來代替它們。我用這個代碼來調試它。

Log::info(var_export(DB::getQueryLog(), true)); 

的日誌是這樣

2 => 
array (
'query' => 'select `id`, `col1`, `col2`, `col3` from `table1` where col1 like \'%?%\' and col2 like \'%?%\' order by `col1` ASC limit 10 offset 0', 
'bindings' => 
    array (
     0 => 'k', 
     1 => '', 
    ), 
'time' => 25.71, 

我想綁定不起作用PR我做錯了。因爲如果我在數據庫中嘗試這個代碼它有效。 (另外,我想是發送到數據庫中的實際SQL。我該怎麼辦呢?)

select `id`, `col1`, `col2`, `col3` from `table1` 
where col1 like '%k%' and col2 like '%%' 
order by `col1` ASC limit 10 offset 0 

回答

0

嘗試

->whereRaw("col1 like '%?%'", [$col1]) 
    ->whereRaw("col2 like '%?%'", [$col2]) 

->whereRaw("col1 like '%?%'", $col1) 
    ->whereRaw("col2 like '%?%'", $col2) 
10

想通了。這個?需要自行完成,因此需要將%符號連接到col變量。並把你的山坳變量數組(假設你使用Laravel 4)

變化:

->whereRaw("col1 like '%?%'", [$col1]) 
->whereRaw("col2 like '%?%'", [$col2]) 

要:

->whereRaw("col1 like ?", array('%'.$col1.'%')) 
->whereRaw("col2 like ?", array('%'.$col2.'%')) 
+0

感謝它workd – muhammedea

+1

我希望我能給予好評於此。有很多錯誤的例子,我正要砍掉我的手腕 – Toskan