【问题标题】:Laravel query builder doesn't bind valuesLaravel 查询生成器不绑定值
【发布时间】:2013-08-19 16:17:57
【问题描述】:

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

【问题讨论】:

    标签: laravel laravel-4


    【解决方案1】:

    想通了。这 ?需要自己去,所以将 % 符号连接到你的 col 变量。并将您的 col 变量放入一个数组中(假设您使用的是 Laravel 4)

    变化:

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

    收件人:

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

    【讨论】:

    • 我希望我能更多地支持这个。周围错误的例子太多了,我都快割腕了
    【解决方案2】:

    试试

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

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

    【讨论】:

      猜你喜欢
      • 2015-04-06
      • 2015-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-10
      • 2019-01-29
      • 2018-11-27
      相关资源
      最近更新 更多