首页 > 解决方案 > Laravel 查询 LIKE 时合并两列

问题描述

我有一个搜索输入?search=xxxx

我的数据库中有两列first_namelast_name. 我希望搜索对他们俩都有效,例如,如果我的输入是John Smith 搜索应该像CONCAT(first_name, last_name) ILIKE %input%

但是 laravel 不允许我这样做:

$customers = $customers->selectRaw("CONCAT('first_name', 'last_name') AS fullname")->where("fullname", "ilike", "%" . $text . "%");

客户已经定义,并且是一个 ORM 对象,而不是集合。

我得到的错误是:

SQLSTATE[42703]: Undefined column: 7 ERROR: column "fullname" does not exist LINE 1: ...) AS fullname from "people" where "type" = $1 and "fullname"... ^ (SQL: select CONCAT('first_name', 'last_name') AS fullname from "people" where "type" = customer and "fullname" ilike %fidel% order by "id" asc)

也试过:

 $customers = $customers->whereRaw("CONCAT('first_name', 'last_name')", "ilike", "%" . $text . "%");

还有一个错误:

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined (SQL: select * from "people" where "type" = customer %fidel% CONCAT('first_name', 'last_name') order by "id" asc)

标签: phpsqllaravel

解决方案


有多个问题:

  • 您不能用单引号将列括起来。使用双引号(或根本不使用引号)。
  • 您不能像fullnameWHERE子句中那样访问派生列。
  • whereRaw()只有两个参数,SQL 字符串和绑定数组。

用这个:

$customers->where(DB::raw('concat("first_name", "last_name")'), 'ilike', '%'.$text.'%');

推荐阅读