Yii2:如何使用orWhere in和Where

时间:2015-04-29 07:08:17

标签: yii yii2

我想用yii2搜索模型

创建此查询
select * from t1 where (title = 'keyword' or content = 'keyword') AND 
                       (category_id = 10 or term_id = 10 )

但我不知道如何使用orFilterWhereandFilterWhere

我在搜索模型中的代码:

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

1 个答案:

答案 0 :(得分:47)

首先,您所需的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]]);
   }...