27

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
Winter
  • 3,278
  • 7
  • 21
  • 49
ingenious
  • 696
  • 1
  • 7
  • 22

1 Answers1

56

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]]);
   }...
sdlins
  • 1,868
  • 1
  • 21
  • 26
user1852788
  • 4,118
  • 23
  • 24