2015-04-29 25 views
20

yılında orWhere kullanmak nasıl yii2 arama modeliYii2: andWhere

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

ile bu sorgu oluşturmak istiyorum Ama orFilterWhere ve andFilterWhere nasıl kullanılacağını bilmiyorum.

arama modelinde Benim kod:

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

    //... 
} 

Ama bu sorguyu oluşturur:

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

cevap

40

Önce gerekli sql staement böyle yetiremediğin olmalıdır:

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

Yani sorgu oluşturucu şu şekilde düşünülmelidir:

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