6

我正在使用这样的 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,

我认为绑定不起作用公关我做错了什么。因为如果我在数据库中尝试此代码它可以工作。(此外,我想获取发送到数据库的实际 sql。我该怎么做?)

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

2 回答 2

11

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.'%'))
于 2013-09-14T18:45:57.223 回答
0

尝试

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

    ->whereRaw("col1 like '%?%'", $col1)
    ->whereRaw("col2 like '%?%'", $col2)
于 2013-08-17T10:06:05.033 回答