phpcodeigniteractiverecordwhere-clauselogical-grouping

How to correctly combine where and or_where (with foreach loop)


I am trying the following code:

//NEEDS TO BE 'OR's
    foreach ($market_ids as $market_id) {
             $this->CI->db->or_where('market_id',$market_id,FALSE);
             }
//NEEDS TO BE 'AND'
    $this->CI->db->where('market_product.product_id',$product_id,FALSE);
    $this->CI->db->from('market_product');
    $this->CI->db->join('product', 'market_product.product_id = product.product_id');

by the result i see that 'where' with the market_product.product_id it also hads a "and". What i need is ('OR's for the markets and one 'AND' for the product_id.) but whatever i tried didn't work.. I also looked at other similar questions in stackoverflow but none of them contains the 'foreach' thing or how to solve it.

Any assistance would be appreciated. I know version 3.0 would solve it by grouping but its not officially released yet.


Solution

  • a way to solve your problem

    //NEEDS TO BE 'OR's
        $where_or = array();
        foreach ($market_ids as $market_id) {
                // $this->CI->db->or_where('market_id',$market_id,FALSE);
             $where_or[] = "market_id = $market_id";
        }
      $this->CI->db->where("(".implode(' OR ',$where_or).")");
    //NEEDS TO BE 'AND'
        $this->CI->db->where('market_product.product_id',$product_id,FALSE);
        $this->CI->db->from('market_product');
        $this->CI->db->join('product', 'market_product.product_id = product.product_id');
    

    hope this will work for you