Php Laravel在查询LIKE时合并两列
我有一个搜索输入Php Laravel在查询LIKE时合并两列,php,sql,laravel,Php,Sql,Laravel,我有一个搜索输入?search=xxxx 我的数据库中有两列first\u name和last\u name。 我希望搜索对它们都有效,例如,如果我的输入是John Smith 搜索应该像CONCAT(名字、姓氏)一样,像%input% 但拉威尔不让我这么做: $customers = $customers->selectRaw("CONCAT('first_name', 'last_name') AS fullname")->where("fullname", "ilike", "
?search=xxxx
我的数据库中有两列first\u name
和last\u name
。
我希望搜索对它们都有效,例如,如果我的输入是John Smith
搜索应该像CONCAT(名字、姓氏)一样,像%input%
但拉威尔不让我这么做:
$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)
根据您编写代码的方式,我不确定您使用的是什么,但如果是sql,这可能就是您想要的
DECLARE @cust_name VARCHAR(100) = 'john smith' -- users input
DECLARE @first_name VARCHAR(50) = SUBSTRING(@cust_name, 1, CHARINDEX(' ', @cust_name) - 1)
DECLARE @last_name VARCHAR(50) = SUBSTRING(@cust_name, CHARINDEX(' ', @cust_name) + 1, 8000)
SELECT CONCAT(c.FirstName,c.LastName)
FROM
customers c
WHERE
c.FirstName = @first_name
AND c.LastName = @last_name
存在多个问题:
- 不能将列用单引号括起来。使用双引号(或完全不使用引号)
- 您不能访问
子句中的WHERE
之类的派生列fullname
只有两个参数:SQL字符串和绑定数组whereRaw()
$customers->where(DB::raw('concat("first_name", "last_name")'), 'ilike', '%'.$text.'%');
您尝试过常规字符串连接吗?->whereraw(“像“%$query%”一样合并(名字+“”+姓氏“”)。我对SQL不是很在行,所以我不确定我喜欢vs是什么,但这是我们的名字和姓氏搜索功能,它工作得很好。这很有趣。sql看起来有效,除了列名周围的双引号外,不确定它为什么会抛出未定义的列。然而,非常奇怪的是,laravel在列名周围添加了双引号。它们不应该在那里。请尝试以下操作:
$result=Customers::where(DB::raw('concat(first_name,“,last_name)”),'LIKE','%keyword%')->get()代码>让我们知道它是否有用。您使用的是什么数据库?我使用的是Postgresql