Yii2 implements the method of searching multiple fields at the same time, and yii2 implements Multiple Fields

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.