Answer the question
In order to leave comments, you need to log in
How to properly search the site?
I'm trying to organize a search on the site for one model (table) as anyone likes and displaying the received data through
ActiveDataProvider таким образом
public function actionSearch($query)
{
$search = Serial::find()->where(['or',['like', 'name_serial', $query],['like', 'description_serial', $query]])->limit(30);
$searchDataprovider = new ActiveDataProvider([
'query' => $search,
'pagination' => [
'pageSize' => 15,
],
]);
return $this->render('search', [
'searchDataprovider' => $searchDataprovider
]);
}
SELECT * FROM `fl_serial` WHERE (`name_serial` LIKE '%Игра престолов%') OR (`description_serial` LIKE '%Игра престолов%') LIMIT 15
SELECT * FROM `fl_serial` WHERE (`name_serial` LIKE '%Елизавета I%') OR (`description_serial` LIKE '%Елизавета I%') LIMIT 15
public function actionSearch($query)
{
$search = Serial::find()->where(['or',['like', 'name_serial', str_replace(' ','%',$query)],['like', 'description_serial', str_replace(' ','%',$query)]])->limit(30);
$searchDataprovider = new ActiveDataProvider([
'query' => $search,
'pagination' => [
'pageSize' => 15,
],
]);
return $this->render('search', [
'searchDataprovider' => $searchDataprovider
]);
}
SELECT * FROM `fl_serial` WHERE (`name_serial` LIKE '%Елизавета//%I%') OR (`description_serial` LIKE '%Елизавета//%I%') LIMIT 15
Answer the question
In order to leave comments, you need to log in
What are you actually expecting to get? www.yiiframework.com/doc-2.0/yii-db-queryinterface...
if you want to search for each word from the query, then first break the query by spaces
public function actionSearch($query)
{
$subqueries = preg_split("/\s/u", $query, -1, PREG_SPLIT_NO_EMPTY);
//Лучше потом отфильровать $subqueries убрав короткие слова или пошаманить с регуляркой что разбивало только если за пробелом слово больше n символов (чтоб Елизавета X так и осталась Елизавета X)
// например так
// $subqueries = preg_split("/\s(?=\w{2,})/u", $query, -1, PREG_SPLIT_NO_EMPTY)
$search = Serial::find()->where(['or',['like', 'name_serial', $subqueries],['like', 'description_serial', $subqueries]]);
$searchDataprovider = new ActiveDataProvider([
'query' => $search,
'pagination' => [
'pageSize' => 15,
],
]);
return $this->render('search', [
'searchDataprovider' => $searchDataprovider
]);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question