phpcodeigniterwhere-clausequery-builderlogical-grouping

or_where inside where function active records


I would like to ask if anyone of you know how to place a or_where inside a where in codeigniter?

I would like to create a query as shown below

select *
from table
where
(
  (in = 0 and call_in = 1) or
  (out = 0 and call_out = 1)
) and
mid = 0
ORDER BY id DESC
limit 1

I have created something like this

$result = $mysql_handler->select('*')
                        ->from("table")
                        ->where(
                               array(
                                 "in"       => 0,
                                 "call_in"  => 1
                               )
                          )
                        ->or_where(
                              array(
                                 "out"      => 0,
                                 "call_out" => 1
                              )
                         )
                        ->where("mid", 0)
                        ->order_by("id", "DESC")
                        ->limit(1)
                        ->get();

But I know this is not right since this code will produce something like this

select *
from table
where
   (in = 0 and call_in = 1) or
   (out = 0 and call_out = 1) and
   mid = 0
ORDER BY id DESC
limit 1

I thinking of placing the or_where inside the where clause but I'm not sure if this is correct or how to do it. Please advice thanks.


Solution

  • You cannot combine where and or_where as you wanted. or_where can be used where only OR queries needed. You can try this for your solution

        $this->db->from('table');
        $this->db->select('*');
        $this->db->where('((in = 0 and call_in = 1) OR (out = 0 and call_out = 1))');
        $this->db->where("mid", 0);
        $this->db->order_by("id", "DESC");
        $this->db->limit(1);
        $result=$this->db->get();
    

    Or

    $result = $mysql_handler->select('*')
            ->from("table")
            ->where('((in = 0 and call_in = 1) OR (out = 0 and call_out = 1))')            
            ->where("mid", 0)
            ->order_by("id", "DESC")
            ->limit(1)
            ->get();