当我尝试向它传递参数时,使用 orWhereRaw() 会引发错误?

时间:2021-06-02 15:13:04

标签: laravel eloquent laravel-8 laravel-query-builder

Laravel 文档在讨论 orWhereRaw() 查询构建器语法时声明了以下内容

<块引用>

whereRaw 和 orWhereRaw 方法可用于注入原始的“where”子句 进入您的查询。这些方法接受一个可选的绑定数组作为它们的 第二个参数:

他们举了以下例子:

$orders = DB::table('orders')
     ->whereRaw('price > IF(state = "TX", ?, 100)', [200])
     ->get();

在下一个示例中,我尝试实现这一点,但在响应中收到错误消息:

<块引用>

SQLSTATE[HY093]: 无效的参数号 (SQL: select count(*) as aggregate from users 其中 LOWER(firstname) LIKE "%dav%" 或 LOWER(lastname) LIKE "%dav%" 或 CONCAT(LOWER(firstname)," ",LOWER(lastname)) LIKE "%dav%" 或 CONCAT(LOWER(address_1)," ",LOWER(address_2)," ",LOWER(address_3)) LIKE "%dav%" 或 CONCAT(LOWER(city)," ",LOWER(state)," ",LOWER(zip_code)) LIKE "%dav%")

这是代码:

$users = User::select('id','firstname', 'lastname', 'dob', 'address_1', 'address_2', 'address_3',
                      'city','state', 'zip_code', 'email', 'mobile_phone','receive_texts',
                      'home_phone', 'work_phone', 'alt_phone', 'member', 'allow_partial_payment', 
                      'wants_information', 'have_attended', 'allow_photos', 'allow_photos_all')
->when(count($sstr)>0, function($query) use ($sstr) {
  foreach($sstr as $str){
     $query->whereRaw('LOWER(`firstname`) LIKE "%?%"', [$str])
        ->orWhereRaw('LOWER(`lastname`) LIKE "%?%"', [$str])
        ->orWhereRaw('CONCAT(LOWER(`firstname`)," ",LOWER(`lastname`)) LIKE "%?%"', [$str])
        ->orWhereRaw('CONCAT(LOWER(`address_1`)," ",LOWER(`address_2`)," ",LOWER(`address_3`)) LIKE "%?%"', [$str])
        ->orWhereRaw('CONCAT(LOWER(`city`)," ",LOWER(`state`)," ",LOWER(`zip_code`)) LIKE "%?%"', [$str]);
    }

 })
 ->orderBy('lastname','asc')->orderBy('firstname','asc')
 ->paginate($this->items_on_page);

但是,如果我将 whereRaw() 部分更改为以下内容,它是否有效?这是为什么?似乎 [] 绑定会更安全一些。以下更改使其正常工作。

foreach($sstr as $str){
   $query->whereRaw('LOWER(`firstname`) LIKE "%' . $str . '%"')
     ->orWhereRaw('LOWER(`lastname`) LIKE "%' . $str . '%"')
     ->orWhereRaw('CONCAT(LOWER(`firstname`)," ",LOWER(`lastname`)) LIKE "%' . $str . '%"')
      ->orWhereRaw('CONCAT(LOWER(`address_1`)," ",LOWER(`address_2`)," ",LOWER(`address_3`)) LIKE "%' . $str . '%"')
      ->orWhereRaw('CONCAT(LOWER(`city`)," ",LOWER(`state`)," ",LOWER(`zip_code`)) LIKE "%' . $str . '%"');
}

0 个答案:

没有答案
相关问题