Saturday, September 7, 2013

Codeigniter: Active Record, or_like and brackets

Fix untuk "DB_active_rec.php".

Edit function "protected function _like", tambahkan yang saya beri color merah.
if ( ! is_array($field)) 
{ 
$field = array($field => $match); 
} 
$prefix = '';
Kemudian, masih di function yang sama dengan yang diatas, pindahkan yang saya beri color biru ke bagian bawah, masih didalam foreach. Lihat line yang saya beri color merah.


$prefix = (count($this->ar_like) == 0) ? '' : $type;
$v = $this->escape_like_str($v); 
if ($side == 'none') 
{ 
  $like_statement = $prefix." $k $not LIKE '{$v}'"; 
}

BECOME
$this->ar_like[] = $like_statement; 
if ($this->ar_caching === TRUE) 
{   
  $this->ar_cache_like[] = $like_statement; 
  $this->ar_cache_exists[] = 'like'; 
} 
$prefix = (count($this->ar_like) == 0) ? '' : $type;

Edit file "/system/database/DB_active_rec.php", tambah function dibawah ini :
var $ar_bracket_open = FALSE; 
var $last_bracket_type = 'where'; 
function bracket($type = NULL,$append='where') 
{

        if ( strtolower($type) == 'open' )
        {
            // fetch the key of the last entry added
            $key = key($this->ar_where);
            $this->ar_bracket_open = TRUE;

            // add a bracket close
            $this->ar_where[$key] = '('.$this->ar_where[$key];
        }
        elseif ( strtolower($type) == 'close' )
        {
            // fetch the key of the last entry added
            if ($append == 'like')    {
                end($this->ar_like);
                $key = key($this->ar_like);

                // add a bracket close
                   $this->ar_like[$key] .= ')';

                // update the AR cache clauses as well
                if ($this->ar_caching === TRUE)
                {
                    $this->ar_cache_like[$key] = $this->ar_like[$key];
                }
            } else {
                end($this->ar_where);
                $key = key($this->ar_where);

                // add a bracket close
                   $this->ar_where[$key] .= ')';

                // update the AR cache clauses as well
                if ($this->ar_caching === TRUE)
                {
                    $this->ar_cache_where[$key] = $this->ar_where[$key];
                }
            }
        }
        return $this;
 Dan cara menggunakannya seperti ini…
//bracket started
$this->db->bracket('open','like'); //bracket closed  
$this->db->or_like(array('field1'=>$filter1, 'field2'=>$filter2)); 
$this->db->bracket('close','like'); //bracket closed 

2 comments:

  1. Very good trick, can you please guide I just want brackets around this->db->like() and this->db->or_like()

    ReplyDelete
  2. But your code is inserting brackets around whole where and likes...

    ReplyDelete