Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2: How to use orWhere in andWhere

Tags:

yii

yii2

I want create this query with yii2 search model

select * from t1 where (title = 'keyword' or content = 'keyword') AND 
                       (category_id = 10 or term_id = 10 )

But I don't know how to use orFilterWhere and andFilterWhere.

My code in search model:

public function search($params) {
   $query = App::find();

   //...

   if ($this->keyword) { 
        $query->orFilterWhere(['like', 'keyword', $this->keyword])
              ->orFilterWhere(['like', 'content', $this->keyword])
   }
   if ($this->cat) {
        $query->orFilterWhere(['category_id'=> $this->cat])
              ->orFilterWhere(['term_id'=> $this->cat])
   }

   //...
}

But it creates this query:

select * from t1 where title = 'keyword' or content = 'keyword' or 
                       category_id = 10 or term_id = 10
like image 862
ingenious Avatar asked Apr 29 '15 07:04

ingenious


1 Answers

First, your required sql statement should be something like this:

select * 
from t1 
where ((title LIKE '%keyword%') or (content LIKE '%keyword%')) 
AND ((category_id = 10) or (term_id = 10))

So your query builder should be something like this:

public function search($params) {
   $query = App::find();
    ...
   if ($this->keyword) { 
        $query->andFilterWhere(['or',
            ['like','title',$this->keyword],
            ['like','content',$this->keyword]]);
   }
   if ($this->cat) {
        $query->andFilterWhere(['or',
            ['category_id'=> $this->cat],
            ['term_id'=> $this->cat]]);
   }...
like image 140
user1852788 Avatar answered Nov 13 '22 16:11

user1852788