Laravel merge two columns when querying LIKE

柔情痞子 提交于 2021-01-28 06:08:31

问题


I have a search input ?search=xxxx

I have two columns in my database first_name and last_name. I want the search to work for both of them, for example if my input is John Smith the search should be like CONCAT(first_name, last_name) ILIKE %input%

But laravel doesn't let me do it:

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

Customers is already defined, and is an ORM object, not collection.

And the error i get for this:

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)

Also tried:

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

And another error:

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)

回答1:


There are multiple problems:

  • You can't wrap columns in single quotes. Use double quotes (or no quotes at all).
  • You can't access derived columns like fullname in the WHERE clause.
  • whereRaw() only has two parameters, the SQL string and an array of bindings.

Use this:

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



回答2:


I'm not sure what it is you are using based on how you are writing your code but if it is sql this might be what you are after...

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


来源:https://stackoverflow.com/questions/51843843/laravel-merge-two-columns-when-querying-like

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!