CodeIgniter活动记录 - 组OR语句 [英] CodeIgniter Active Record - Group OR statements

查看:82
本文介绍了CodeIgniter活动记录 - 组OR语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题: MySQL或条件

解决方案是对OR语句进行分组,但是我使用CodeIgniters Active Record。有没有办法使用Active Record对OR语句进行分组?

The solution is to group the OR statements, but i'm using CodeIgniters Active Record. Is there a way to group OR statements using Active Record? Or do I have to write the query myself?

我使用 $ this-> db-> where() $ this-> db-> or_where()

这:

WHERE title ='foobar'AND category = 2 OR category = 3

但我需要的是:

WHERE title ='foobar'AND(category = 3)

我无法做到:

$this->db->where("title = 'foobar' AND (category = 2 OR category = 3)");

因为我使用foreach循环添加ORs

because i'm adding ORs using a foreach loop

推荐答案

您可以按照此处


自定义字符串:您可以手动编写自己的子句:

Custom string: You can write your own clauses manually:

$ where =name ='Joe'AND status ='boss'OR status ='active';

$where = "name='Joe' AND status='boss' OR status='active'";

$ this-> db- > where($ where);

$this->db->where($where);

至于您的问题:

$this->db->where("category = 1 AND (category = 2 OR category = 3)");

3.0-dev 中:

$this->db->select()
->group_start()
->or_like([ 'category' => 2, 'category' => 3 ])
->group_end()                
->where([ 'category' => 1 ]);



更新



a href =http://stackoverflow.com/questions/6470267/grouping-where-clauses-in-codeigniter>此问题,如果您使用CI 2.2。

update

See the answers on this question if you're using CI 2.2. Choose an answer other than the accepted.

或直接尝试 this

$categories = array(2, 3);

array_walk($categories, function(&$cat) { $cat = 'category = ' . $cat; });

$catstring  = implode(" OR ", $categories);
$where      = "category = 1 AND ($catstring)";
// => category = 1 AND (category = 2 OR category = 3)

$this->db->where($where);

这篇关于CodeIgniter活动记录 - 组OR语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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