首页 > 解决方案 > Yii2 搜索模型

问题描述

在我的网站上,当我搜索 Alex Lau 时,我会显示结果 Alex Lau。问题是如何修改代码,所以当我搜索 Lau Alex 时,它仍然会显示 Alex Lau 结果。现在它没有。

$query->orFilterWhere(['like', 'fullname', $this->globalSearch])

这是我的搜索模型中的代码。

请帮我解决一下这个。

谢谢!

标签: yii2yii2-basic-app

解决方案


根据 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 JohnJohn Alex Lau Lau John Alex


推荐阅读