phpmysqlcodeigniterwhere-clauselogical-grouping

How to encapsulate AND and OR logic using CodeIgniter query building methods?


My Query :

$this->db->select('*');
$this->db->join('pos_item_sales', 'pos_item_sales.item_id = pos_item_infos.item_id');
$this->db->join('pos_batch_infos', 'pos_batch_infos.item_id = pos_item_infos.item_id');
$this->db->where("`pos_item_sales`.`transaction_id` =  '$transaction_id' AND (`pos_item_sales`.`item_barcode` =  '$term' OR `pos_batch_infos`.`item_mbarcode` =  '$term' OR `pos_item_infos`.`item_id` =  '$term')");
$query = $this->db->get('pos_item_infos');
echo $this->db->last_query();

its solve my prob but i need like this query :

$term = $this->input->get('term',TRUE);
$this->db->select('*');
$this->db->join('pos_item_sales', 'pos_item_sales.item_id = pos_item_infos.item_id');
$this->db->join('pos_batch_infos', 'pos_batch_infos.item_id = pos_item_infos.item_id');
$this->db->where('pos_item_sales.transaction_id',$transaction_id);
$this->db->where('pos_item_sales.item_barcode',$term);
$this->db->or_where('pos_batch_infos.item_mbarcode',$term);
$this->db->or_where('pos_item_infos.item_id',$term);
$query = $this->db->get('pos_item_infos');
echo $this->db->last_query();

But I need a Query like :

SELECT *
FROM (`pos_item_infos`)
JOIN `pos_item_sales` ON `pos_item_sales`.`item_id` = `pos_item_infos`.`item_id`
JOIN `pos_batch_infos` ON `pos_batch_infos`.`item_id` = `pos_item_infos`.`item_id`
WHERE `pos_item_sales`.`transaction_id` =  '11355822927'
AND (`pos_item_sales`.`item_barcode` =  '8801962686156'
OR `pos_batch_infos`.`item_mbarcode` =  '8801962686156'
OR `pos_item_infos`.`item_id` =  '8801962686156')

How can I solve this problem? It's not include ( ) in my or condition.


Solution

  • if you go through the codeigniter userguide.. you can see that there are 4 ways to call where clause...

    All of these does the same things... and your first code is codeigniter style (if incase you are worried that is not) that is the 4th method by codeigniter userguide where you can write your own clauses manually... there is no difference in calling the where function in anyways...

    so i would go with your first query

    $this->db->select('*');
    $this->db->join('pos_item_sales', 'pos_item_sales.item_id = pos_item_infos.item_id');
    $this->db->join('pos_batch_infos', 'pos_batch_infos.item_id = pos_item_infos.item_id');
    $this->db->where("`pos_item_sales`.`transaction_id` =  '$transaction_id' AND (`pos_item_sales`.`item_barcode` =  '$term' OR `pos_batch_infos`.`item_mbarcode` =  '$term' OR `pos_item_infos`.`item_id` =  '$term')");
    $query = $this->db->get('pos_item_infos');
    echo $this->db->last_query();
    

    which is perfectly fine...