笨 - 分组where子句(CodeIgniter - Grouping where clause)

2019-09-18 11:31发布

我有这个笨以下查询:

$q = $this->db->where('(message_from="'.$user_id.'" AND message_to="'.$this->auth_model->userdata['user_id'].'")')
            ->or_where('(message_from="'.$this->auth_model->userdata['user_id'].'" AND message_to="'.$user_id.'")')
            ->get('messages');

我想写这个查询具有完全的活动记录。

我已经试过这样的事情:

$from_where = array('message_from'=>$user_id, 'message_to'=>$this->auth_model->userdata['user_id']);
            $to_where   = array('message_from'=>$this->auth_model->userdata['user_id'],'message_to'=>$user_id);    
            $q = $this->db->where($from_where)
            ->or_where($to_where)
            ->get('messages');

            die($this->db->last_query());

以上代码生成此查询:

SELECT * FROM (`messages`) WHERE `message_from` = '2' AND `message_to` = '1' OR `message_from` = '1' OR `message_to` = '2'

但是,这是我想生产什么:

SELECT * FROM (`messages`) WHERE (message_from="2" AND message_to="1") OR (message_from="1" AND message_to="2")

有类似的问题在这里和这里 ,但thosedid不是为我提供了一个真正的解决方案。

这个怎么可能,如果不通过核心库,是有一个扩展,它允许写这样的疑问?

谢谢,

Answer 1:

您可以使用笨的子查询的方式为这个目的,你将不得不破解笨做到这一点。 这样进入系统/数据库/ DB_active_rec.php删除这些功能的公共或受保护的关键字

public function _compile_select($select_override = FALSE)
public function _reset_select()

现在,子查询写入可用,现在这里是有活动记录查询

$this->db->where('message_from','2');
$this->db->where('message_to','1');

$subQuery1 = $this->db->_compile_select();
$this->db->_reset_select();


$this->db->where('message_from','1');
$this->db->where('message_to','2');

$subQuery2 = $this->db->_compile_select();
$this->db->_reset_select();

$this->db->select('*');
$this->db->where("$subQuery1");
$this->db->or_where("$subQuery2");
$this->db->get('messages');

看看这个回答我的。 这展示了如何使用子查询。 这将有助于
使用MySQL凡在笨条款

编辑

是的,我已经做了重写查询这种方式正是你想要

$this->db->where('message_from','2');
$this->db->where('message_to','1');

$subQuery1 = $this->db->_compile_select(TRUE);
$this->db->_reset_select();


$this->db->where('message_from','1');
$this->db->where('message_to','2');

$subQuery2 = $this->db->_compile_select(TRUE);
$this->db->_reset_select();

$this->db->select('*');
$this->db->where("($subQuery1)");
$this->db->or_where("($subQuery2)");
$this->db->get('messages');

编译选择是正确的参数。 不会产生SELECT子句。 这将产生

SELECT * FROM (`messages`) WHERE (`message_from` = '2' AND `message_to` = '1') OR (`message_from` = '1' AND `message_to` = '2')


文章来源: CodeIgniter - Grouping where clause