Laravel 查询构建器不绑定(bind)值

标签 laravel laravel-4

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

我认为绑定(bind)不起作用,因为我做错了什么。因为如果我在数据库中尝试这段代码它就会起作用。 (另外,我想获取发送到数据库的实际sql。我该怎么做?)

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

最佳答案

想通了。这 ?需要单独运行,因此将 % 符号连接到您的 col 变量。并将你的 col 变量放入一个数组中(假设你使用的是 Laravel 4)

更改:

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

致:

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

关于Laravel 查询构建器不绑定(bind)值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18287190/

相关文章:

laravel - 如何在 Visual Studio Code 中启用 PHP 类建议?

php - Laravel 5 Elixir : copy all files except some

namespaces - Laravel - Eloquent : Polymorphic relations with namespace

php - 拉拉维尔 : Route not found error

laravel-4 - php artisan 服务无法使用不同的端口

php - 尝试使用 laravel css3 和 bootstrap 覆盖图像

javascript - 当用户关闭浏览器选项卡时如何显示弹出窗口?

mysql - 在 Laravel 4 中查询数据透视表

php - SQL 模式 only_full_group_by 在 Lumen 5.7 中导致错误

Laravel select like %value% 通配符查询