2015-04-29 22 views
20

Tôi muốn tạo truy vấn này với mô hình tìm kiếm yii2Yii2: Làm thế nào để sử dụng orWhere trong andWhere

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

Nhưng tôi không biết làm thế nào để sử dụng orFilterWhereandFilterWhere.

Mã của tôi trong mô hình tìm kiếm:

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

    //... 
} 

Nhưng nó tạo ra truy vấn này:

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

Trả lời

40

Đầu tiên cần sql staement của bạn nên được smth như thế này:

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

Vì vậy bạn trình tạo truy vấn phải có dạng như sau:

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]]); 
    }... 
Các vấn đề liên quan