2015-04-29 23 views
20

voglio creare questa query con ricerca yii2 modelloYii2: Come usare orWhere in andwhere

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

Ma io non so come utilizzare orFilterWhere e andFilterWhere.

Il mio codice nel modello di ricerca:

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

    //... 
} 

Ma crea questa query:

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

risposta

40

In primo luogo lo staement SQL richiesto dovrebbe essere smth come questo:

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

Quindi la tua Query Builder dovrebbe essere smth come questo:

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