【问题标题】:Laravel merge two columns when querying LIKELaravel 查询 LIKE 时合并两列
【发布时间】:2018-08-14 14:29:20
【问题描述】:

我有一个搜索输入?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 . "%");

Customers 已经定义,是一个 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)

【问题讨论】:

  • 您是否尝试过常规字符串连接? ->whereraw("COALESCE(first_name + ' ' + last_name, '') LIKE '%$query%'").我不太擅长 SQL,所以我不确定 ILIKE 和 LIKE 是什么,但这是我们的名字和姓氏搜索功能,效果很好。
  • 这很有趣。 sql 看起来有效,除了列名周围的双引号,不知道为什么它会抛出未定义的列。然而,很奇怪,laravel 在列名周围添加了双引号。他们不应该在那里。
  • 试试这个:$result = Customers::where(DB::raw('concat(first_name," ",last_name)') , 'LIKE' , '%keyword%')->get(); 让我们知道它是否有帮助。
  • 你用的是什么数据库?
  • 我正在使用 Postgresql

标签: php sql laravel


【解决方案1】:

有多个问题:

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

使用这个:

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

【讨论】:

    【解决方案2】:

    根据您编写代码的方式,我不确定您使用的是什么,但如果是 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-24
      • 1970-01-01
      • 1970-01-01
      • 2015-04-17
      • 1970-01-01
      • 2019-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多