Yii2 realizes the method of searching multiple fields at the same time_php example

WBOY
Release: 2016-08-17 13:02:31
Original
1207 people have browsed it

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 the method orFilterWhere

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

Readers who are interested in more Yii-related content can check out the special topics of this site: "Introduction to Yii Framework and Summary of Common Techniques", "Summary of Excellent Development Framework of PHP", "Basic Tutorial for Getting Started with Smarty Templates", "Introduction to PHP Object-Oriented Programming" Tutorial", "php string (string) usage summary", "php+mysql database operation introductory tutorial" and "php common database operation skills summary"

I hope this article will help you design PHP programs based on the Yii framework.

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