【问题标题】:Yii2 search modelYii2 搜索模型
【发布时间】:2018-11-29 21:53:47
【问题描述】:

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

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

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

请帮帮我。

谢谢!

【问题讨论】:

  • globalSearch 变量包含什么?
  • 你需要全文搜索这样的功能吗?
  • Alex Lau 与 Lau Alex 是不同的字符串,所以我认为你必须分成 2 个不同的字符串并使用 2 个 where 条件进行搜索。
  • 您可以分隔单词并循环遍历每个单词并为其准备查询。 Ref

标签: yii2 yii2-basic-app


【解决方案1】:

根据 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

【讨论】:

    【解决方案2】:

    试试这个

    $words = explode(' ',$this->globalSearch);
    
    if (count($words) > 1) {
        foreach ($words as $word) {
            $query->orFilterWhere(['like', 'fullname', $word]);
        }
    } else {
        $query->orFilterWhere(['like', 'fullname', $this->globalSearch]);
    }
    

    注意:您需要确保空格

    【讨论】:

    • 谢谢,我正在测试这个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多