将 or_where 限制为 codeigniter 中 2 个位置之间的特定位置

restrict or_where to a specific where between 2 wheres in codeigniter

我有这个代码:

    $this->db->where('status',1);
    $this->db->where('category',$category_id);
    $this->db->or_where('parent_category',$category_id);
    $this->db->or_where('grandParent_category',$category_id);
    $this->db->or_where('parentOfGP_category',$category_id);
    $query = $this->db->get('posts');

问题是第一个 where 被覆盖了,它也得到了状态为 0 和 2 的人,因为下一个 or_wheres 相反,我希望 or_wheres 只用于 where( 'category',$category_id);而不是状态

有没有办法在 codeigniter 中做到这一点?

您可以直接传递查询而不是使用 Active Records 作为:

$query = $this->db->query('SELECT name, title, email FROM my_table');

此外,如果您想确定上面的 Active Record 查询究竟形成了什么,请使用以下方法:

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

这有点复杂,因为您要连接 ANDOR 条件。看看这里:Codeigniter Doku

所以对于你的情况应该是这样的:

$this->db->select('*')->from('posts')
  ->group_start()
    ->where('category', $category_id)
    ->or_group_start()
      ->where('parent_category', $category_id)
    ->group_end()
    ->or_group_start()
      ->where('grandParent_category', $category_id);
    ->group_end()
    ->or_group_start()
      ->where('parentOfGP_category', $category_id);
    ->group_end()
  ->group_end()
  ->where('status', 1)
->get();

此代码未经测试。您可能需要调整一些东西。