Yii2 realizes the method of searching multiple fields at the same time

不言
Release: 2023-03-25 16:46:01
Original
1591 people have browsed it

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,
  ]);
}
Copy after login

You can see the sql statement as follows:

Copy code The 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
Copy after login

Related recommendations:

Yii implements two methods of adding default values ​​to models

The above is the detailed content of Yii2 realizes the method of searching multiple fields at the same time. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template