php - Laravel 查询 LIKE 时合并两列
问题描述
我有一个搜索输入?search=xxxx
我的数据库中有两列first_name
,last_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)
解决方案
有多个问题:
- 您不能用单引号将列括起来。使用双引号(或根本不使用引号)。
- 您不能像
fullname
在WHERE
子句中那样访问派生列。 whereRaw()
只有两个参数,SQL 字符串和绑定数组。
用这个:
$customers->where(DB::raw('concat("first_name", "last_name")'), 'ilike', '%'.$text.'%');
推荐阅读
- angular - 如何在字符串中显示信息?
- python - PI Camera 无法与断开的显示器一起工作
- javascript - Angular.js:为什么 ng-model 在引用不存在的属性时不会抛出“Uncaught TypeError”异常?
- spring - 使用 Spring-boot 创建 Shared-Durable 订阅者
- css - 尽管定义了表格并应用固定表格布局,但表格的每一列都有不同的宽度
- angular - angular 6 pwa 无法正常工作
- java - 如何在 Android 中以编程方式将图标设置为警报对话框
- swift - Swift 4 - 创建具有 2 种背景颜色的 UIView
- python - ASCII Characters Text Align
- swift - 按下按钮时,如何将表格视图中单元格的索引从一个视图控制器传递到下一个视图控制器?