2

On my website, when I search Alex Lau, I will show the result Alex Lau. The problem is how can I modify the code so when I search Lau Alex maybe, It will still show Alex Lau result. Right now it didn't.

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

Here is the code in my search model.

Please help me with this.

Thank you!

Sao Ho
  • 139
  • 2
  • 22

2 Answers2

1

Try this

$words = explode(' ',$this->globalSearch);

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

Note: You need to make sure about white spaces

Vidhyut Pandya
  • 1,605
  • 1
  • 14
  • 27
1

A better approach according to the MYSQL query using CONCAT()like below

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] . '"),"%")')]
        );
    }

}

NOTE: This works correctly if you are searching the name in the format first last or first middle last, means you can search Alex Lau John or John Alex Lau Lau John Alex

Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68