Last active
January 28, 2017 06:34
-
-
Save Insolita/1027377ad348e46fb3298c05e6bb9ad2 to your computer and use it in GitHub Desktop.
Полнотекстовый поиск postgres+yii2 - использование
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//-------------------------------------- | |
/** | |
* @param string $query | |
* | |
* @return string | |
*/ | |
public function prepareQuery(string $query):string | |
{ | |
$query = array_filter(explode(' ', mb_strtolower($query)), 'trim'); | |
if (count($query) < 2) { | |
$query = implode('', $query) . ':*'; | |
} else { | |
$query = implode(' & ', $query) . ':*'; | |
} | |
return $query; | |
} | |
/** | |
* @param string $query | |
* @param int $cat | |
* | |
* @return array | |
*/ | |
public function findSuggest(string $query, int $cat = null): array | |
{ | |
$query = $this->prepareQuery($query); | |
$tQuery = (new Query())->from('{{%tovar}}') | |
->select([ | |
'{{%tovar}}.id', | |
'{{%tovar}}.name', | |
'{{%tovar}}.slug', | |
'{{%category}}.name as category', | |
new Expression('ts_rank({{%tovar}}.fts,to_tsquery(:q)) as rank'), | |
]) | |
->leftJoin('{{%category}}','{{%tovar}}.category_id={{%category}}.id') | |
->where(new Expression("{{%tovar}}.fts @@ to_tsquery(:q)", [':q' => $query])) | |
->limit(10) | |
->orderBy(['rank' => SORT_DESC]); | |
if($cat > 0){ | |
$tQuery->andWhere(['{{%tovar}}.category_id'=>$cat]); | |
} | |
return $tQuery->all(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment