Yii2:如何使用或Where in和Where

6yoyoihd  于 2022-11-09  发布在  其他
关注(0)|答案(1)|浏览(421)

我想用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
niknxzdl

niknxzdl1#

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

相关问题