Yii2 implements the method of searching multiple fields at the same time, and yii2 implements Multiple Fields
This example describes how Yii2 can search multiple fields at the same time. We will share this with you for your reference. The details are as follows:
In Yii2, The andFilterWhere method is used to search for a field.
If multiple fields are to be searched, for example, whether or not the title and content of a search article contain the keywords to be searched. because the relationship between the two fields is or, the orFilterWhere method is required.
Below is all the code
public function actionIndex(){ $key =Yii::$app->request->post("key"); $query = Post::find()->joinWith('cate'); $post = $query->orderBy(['post.id' => SORT_DESC])->asArray()->where(['post.status' => 1]); if($key){ $post->andFilterWhere(['like', 'post.title', $key]) ->orFilterWhere(['like', 'post.content', $key]); } $pages = new Pagination([ 'totalCount' => $post->count(), 'defaultPageSize' => 10 ]); $model = $post->offset($pages->offset)->limit($pages->limit)->all(); return $this->render('index', [ 'model' => $model, 'pages' => $pages, ]);}
The SQL statement is as follows:
Copy codeThe Code is as follows: select count (*) from 'post' left join 'category 'on 'post '. 'cate _ id' = 'category '. 'id' where ('post '. 'status' = 1) and ('post '. 'title' like '% key %') or ('post '. 'content' like '% key %') order by 'post '. 'id' desc
Select 'post '. * from 'post' left join 'category 'on 'post '. 'cate _ id' = 'category '. 'id' where ('post '. 'status' = 1) and ('post '. 'title' like '% key %') or ('post '. 'content' like '% key %') order by 'post '. 'id' desc limit 10