2015-04-29 7 views
20

Ich mag diese Abfrage mit Modell yii2 Suche erstellenYii2: Wie orWhere in UndWo verwendet

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

Aber ich weiß nicht, wie orFilterWhere und andFilterWhere zu verwenden.

Mein Code auf der Suche Modell:

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]) 
    } 

    //... 
} 

Aber es schafft, diese Abfrage:

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

Antwort

40

zunächst Ihre gewünschten SQL staement sollte smth so aussehen:

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

So Ihre Abfrage Builder sollte sth wie folgt sein:

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]]); 
    }...