yii2 - Yii2 搜索模型
问题描述
在我的网站上,当我搜索 Alex Lau 时,我会显示结果 Alex Lau。问题是如何修改代码,所以当我搜索 Lau Alex 时,它仍然会显示 Alex Lau 结果。现在它没有。
$query->orFilterWhere(['like', 'fullname', $this->globalSearch])
这是我的搜索模型中的代码。
请帮我解决一下这个。
谢谢!
解决方案
根据 MYSQL 查询使用CONCAT()
如下所示的更好方法
if( $this->fullname!== null && $this->fullname !== '' ){
$searchTerms = explode(" ", $this->fullname);
if( sizeof($searchTerms) > 1 ){
$conditions[]='OR';
foreach( $searchTerms as $term ){
$conditions[] = ['like', 'fullname', new \yii\db\Expression('CONCAT(CONCAT("%","' . $term . '"),"%")')];
}
$query->orFilterWhere($conditions);
} else{
$query->orFilterWhere(
['like', 'fullname', new \yii\db\Expression('CONCAT(CONCAT("%","' . $searchTerms[0] . '"),"%")')]
);
}
}
first last
注意:如果您以或格式搜索名称,这将正常工作first middle last
,这意味着您可以搜索Alex Lau John
或John Alex Lau
Lau John Alex
推荐阅读
- r - 如何让 Forestplot 函数在 r 中工作?
- angular - Angular 多组件渲染视图问题
- python - 无法使用收集 RDD
- python - jsonpickle:如何正确编码和显示重复对象而不是引用?
- mongodb - MongoDB Mongoose - 鉴别器性能
- python-3.x - 用于计算介于 ! 之间的字符的 Python 程序 和 2 ##
- c++ - 具有泛型类的模板
- git - 我应该什么时候使用 git add,在对文件进行更改之前或之后?
- logging - 在 Docker 应用程序中使用 Logback 更改动态日志级别
- javascript - 如何在 javascript 中处理两个 API 调用?