Yii2實(shí)現(xiàn)同時(shí)搜索多個(gè)字段的方法

字號(hào):


    本文實(shí)例講述了Yii2實(shí)現(xiàn)同時(shí)搜索多個(gè)字段的方法。分享給大家供大家參考,具體如下:
    Yii2中搜索字段是用的andFilterWhere這個(gè)方法,用它可以搜索一個(gè)一段。
    如果是搜索多個(gè)字段的話 ,比如搜索文章標(biāo)題和文章內(nèi)容是是否包含需要搜索的關(guān)鍵詞,因?yàn)樗麄儍蓚€(gè)的關(guān)系是or,所以就要用到orFilterWhere這個(gè)方法
    下面就是全部的代碼
    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,
      ]);
    }
    可以看到sql語(yǔ)句如下:
    代碼如下:
    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
    希望本文所述對(duì)大家基于Yii框架的PHP程序設(shè)計(jì)有所幫助。