代码之家  ›  专栏  ›  技术社区  ›  Ben Beri

Laravel在查询like时合并两列

  •  0
  • Ben Beri  · 技术社区  · 7 年前

    我有搜索输入 ?search=xxxx

    我的数据库中有两列 first_name last_name . 例如,如果我的输入是 John Smith 搜索应该像 CONCAT(first_name, last_name) ILIKE %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)
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Jonas Staudenmeir    7 年前

    有多个问题:

    • 不能用单引号括住列。使用双引号(或完全不使用引号)。
    • 不能访问派生列,例如 fullname WHERE 条款。
    • whereRaw() 只有两个参数,即SQL字符串和绑定数组。

    使用此:

    $customers->where(DB::raw('concat("first_name", "last_name")'), 'ilike', '%'.$text.'%');
    
        2
  •  0
  •   Bob The Builder    7 年前

    我不确定您使用的是什么,基于您编写代码的方式,但如果是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
    
    推荐文章