Yii2搜索模型
在我的网站上,当我搜索Alex Lau时,我会显示结果Alex Lau。问题是我如何修改代码,这样当我搜索Alex时,它仍然会显示Alex Lau的结果。现在没有Yii2搜索模型,yii2,yii2-basic-app,Yii2,Yii2 Basic App,在我的网站上,当我搜索Alex Lau时,我会显示结果Alex Lau。问题是我如何修改代码,这样当我搜索Alex时,它仍然会显示Alex Lau的结果。现在没有 $query->orFilterWhere(['like', 'fullname', $this->globalSearch]) 下面是我的搜索模型中的代码 请帮我做这个 谢谢大家! 试试这个 $words = explode(' ',$this->globalSearch); if (count($words)
$query->orFilterWhere(['like', 'fullname', $this->globalSearch])
下面是我的搜索模型中的代码
请帮我做这个
谢谢大家! 试试这个
$words = explode(' ',$this->globalSearch);
if (count($words) > 1) {
foreach ($words as $word) {
$query->orFilterWhere(['like', 'fullname', $word]);
}
} else {
$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] . '"),"%")')]
);
}
}
注意:如果您正在以
最早
或最早中间最晚
的格式搜索名称,则此操作正确,意思是你可以搜索Alex Lau John
或John Alex Lau
Lau John Alex
globalSearch变量包含什么?你需要像全文搜索这样的功能吗?Alex Lau与Lau Alex是一个不同的字符串,所以我认为你必须分成两个不同的字符串,并使用两个where条件进行搜索。你可以分隔单词然后循环遍历每个单词并为其准备查询。谢谢,我现在正在测试这个。