Yii2:如何在andWhere中使用orWhere

Yii2:如何在andWhere中使用orWhere,yii,yii2,Yii,Yii2,我想用yii2搜索模型创建此查询 select * from t1 where (title = 'keyword' or content = 'keyword') AND (category_id = 10 or term_id = 10 ) 但是我不知道如何使用或filterwhere和和filterwhere 搜索模型中的我的代码: public function search($params) { $query = App::fin

我想用yii2搜索模型创建此查询

select * from t1 where (title = 'keyword' or content = 'keyword') AND 
                       (category_id = 10 or term_id = 10 )
但是我不知道如何使用
或filterwhere
和filterwhere

搜索模型中的我的代码:

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

   //...
}
但它创建了这个查询:

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

首先,您需要的sql语句应该是这样的:

select * 
from t1 
where ((title LIKE '%keyword%') or (content LIKE '%keyword%')) 
AND ((category_id = 10) or (term_id = 10))
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]]);
   }...
因此,您的查询生成器应该如下所示:

select * 
from t1 
where ((title LIKE '%keyword%') or (content LIKE '%keyword%')) 
AND ((category_id = 10) or (term_id = 10))
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]]);
   }...