Yii2:如何使用 orWhere in 和Where

标签 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

最佳答案

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

关于Yii2:如何使用 orWhere in 和Where,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29936611/

相关文章:

javascript - Yii2:如何将 JSON 加载到 GridView 中?

mysql - Yii2 使用循环打印列名及其值

forms - Yii2 - 仅在点击提交按钮时提交事件表单,而不是在按下回车键时

mysql - 我想在 yii 中自动使用另一个模型中的一个表主键

php - 对于初学者来说,Laravel 和 Yii 框架哪个更容易理解?

php - MySQL 命令转换为 Yii create

php - 在 Yii2 中使用 plpgsql 绑定(bind)查询值

activerecord - Yii2:ActiveRecord 如何卸载/取消设置所有(某些)属性的模型?

css - Netbeans 8.0 Yii Project Bootstrap LESS 文件有错误

javascript - 如何在我的 js 文件之前运行 yii 表单验证