I am using laravel query builder like this.
$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();
I am getting nothing. If I use toSql() function. I am getting this SQL like this
select `id`, `col1`, `col2`, `col3`
from `table1` where col1 like '%?%' and col2 like '%?%'
order by `col1` ASC limit 10 offset 0
The question marks shouldn't be there. It must replace them with the values. I used this code to debug it.
Log::info(var_export(DB::getQueryLog(), true));
The Logs look like this
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,
I think bindings doesn't work pr I'm doing something wrong. Because If I try this code in database It works. (In Addition, I want to get the actual sql that send to the database. How do I do that?)
select `id`, `col1`, `col2`, `col3` from `table1`
where col1 like '%k%' and col2 like '%%'
order by `col1` ASC limit 10 offset 0
Figured it out. The ? needs to go by itself, so concatenate the % symbols to your col variables. And put your col variables in an array (assuming you're using Laravel 4)
Change:
->whereRaw("col1 like '%?%'", [$col1])
->whereRaw("col2 like '%?%'", [$col2])
To:
->whereRaw("col1 like ?", array('%'.$col1.'%'))
->whereRaw("col2 like ?", array('%'.$col2.'%'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With