在 Codeigniter 中对 WHERE 子句进行分组 [英] Grouping WHERE clauses in Codeigniter

查看:21
本文介绍了在 Codeigniter 中对 WHERE 子句进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Codeigniter 中使用 Active Record 生成以下 SQL 代码:

I want to produce the following SQL code using Active Records in Codeigniter:

WHERE name != 'Joe' AND (age < 69 OR id > 50)

做以下似乎是我所能做到的,我不知道如何将它们分组

Doing the following seems to be as far as I can get, I cant figure out how to group them

$this->db->select()->from('users')->where('name !=', 'Joe')->where('age <', 69)->or_where('id <', $id); 

有什么想法吗?我的 SQL 查询太复杂了,所以我不想用传统的 SQL 重写所有内容.

Any ideas? My SQL query is too complex so I dont wish to rewrite everything in traditional SQL.

更新

我的 SQL 代码是根据传递给模型方法的某些参数的值动态生成的.无法使用括号的问题会导致问题,因为运算符的优先级使得 ANDOR 之前首先被评估.

My SQL code is dynamically generated depending on the values of certain parameters passed into the model method. The problem with not being able to use parenthesis causes a problem because the operator precedence is such that AND is evaluated first before OR.

*这是我的活动记录代码的一部分,在它之前和之后还有一些其他代码:

*Here is a chunk of my active records code, where there are some other code before and after it:

            ... some $this->db->where() ...
            ... some $this->db->where() ...

    if($price_range) {
        $price_array = explode('.', $price_range);
        for($i = 0; $i < count($price_array); $i++) {
            if($i == 0) {
                $this->db->where('places.price_range', $price_array[$i]);
            } else {
                $this->db->or_where('places.price_range', $price_array[$i]);
            }
        }

    }

            ... some $this->db->where() ...
            ... some $this->db->where() ...

问题出现是因为我使用了 $this->db->or_where(),它引入了一个 OR 子句,该子句将运算符优先级置于混乱状态而不会被可以使用 ( ) 来改变顺序.

The problem comes because I am using $this->db->or_where() which introduces a OR clause that throws the operator precedence into disarray without being able to use ( ) to change the order.

** 有没有办法解决这个问题?**

** Is there any way to solve this? **

推荐答案

已解决.动态生成 SQL 查询并将其插入 $this->db->where().谢谢各位!

Solved. Dynamically generate the SQL query and plug it into $this->db->where(). Thanks guys!

这篇关于在 Codeigniter 中对 WHERE 子句进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆