Yii2 搜索模型
Yii2 search model
在我的网站上,当我搜索 Alex Lau 时,我会显示结果 Alex Lau。问题是我如何修改代码,这样当我搜索 Lau Alex 时,它可能仍会显示 Alex Lau 结果。现在还没有。
$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] . '"),"%")')]
);
}
}
注意:如果您搜索格式为 first last
或 first middle last
的名称,这将正常工作,这意味着您可以搜索 Alex Lau John
或 John Alex Lau
Lau John Alex
在我的网站上,当我搜索 Alex Lau 时,我会显示结果 Alex Lau。问题是我如何修改代码,这样当我搜索 Lau Alex 时,它可能仍会显示 Alex Lau 结果。现在还没有。
$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] . '"),"%")')]
);
}
}
注意:如果您搜索格式为 first last
或 first middle last
的名称,这将正常工作,这意味着您可以搜索 Alex Lau John
或 John Alex Lau
Lau John Alex