This article mainly introduces the method of Yii2 to realize simultaneous search of multiple fields. It analyzes the functions and specific usage methods used in Yii2 to search multiple fields at the same time in the form of examples. Friends in need can refer to the following
The example in this article describes how Yii2 implements simultaneous search of multiple fields. Share it with everyone for your reference, the details are as follows:
The search field in Yii2 uses the andFilterWhere method, which can be used to search for a paragraph.
If you are searching for multiple fields, for example, searching whether the article title and article content contain the keywords you need to search for, because the relationship between them is or, so you need to use orFilterWhereThis method
The following 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, ]); }
You can see the sql statement 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
The above is the entire content of this article, I hope it will be helpful to everyone's study , please pay attention to the PHP Chinese website for more related content!
Related recommendations:
How to implement Command task processing through Yii
Use Yii2 rbac permission control menu menu
The above is the detailed content of How to achieve simultaneous search of multiple fields in Yii2. For more information, please follow other related articles on the PHP Chinese website!