Mysql
 sql >> Database >  >> RDS >> Mysql

Utilizzando CodeIgniter get_where per concatenare le istruzioni 'and' e 'or'

A partire da Codeigniter 3.0 la classe Query Builder supporta Raggruppamento di query

dai documenti:

$this->db->select('*')->from('my_table')
        ->group_start()
                ->where('a', 'a')
                ->or_group_start()
                        ->where('b', 'b')
                        ->where('c', 'c')
                ->group_end()
        ->group_end()
        ->where('d', 'd')
->get();

// Generates:
// SELECT * FROM (`my_table`) WHERE ( `a` = 'a' OR ( `b` = 'b' AND `c` = 'c' ) ) AND `d` = 'd'

Modifica: nel tuo esempio useresti:

$this->db->select('message, created')->from('logs')
        ->where('username', 'user')
        ->group_start()
                ->where('created >', '1487695796')
                ->where('created <', '1487782196')
        ->group_end()
        ->group_start()
                ->where('message', 'login failure')
                ->or_where('message', 'login success')
                ->or_where('message', 'log out')
        ->group_end()               
        ->order_by('created', 'ASC')  
->get(); 

o

$this->db->select('message, created')
        ->group_start()
                ->where('created >', '1487695796')
                ->where('created <', '1487782196')
        ->group_end()
        ->group_start()
                ->where('message', 'login failure')
                ->or_where('message', 'login success')
                ->or_where('message', 'log out')
        ->group_end()               
        ->order_by('created', 'ASC')  
->get_where('logs', array('username' => 'user') );

// both generate:
//SELECT `message`, `created` 
//FROM `logs` 
//WHERE `username` = 'user' 
//AND ( `created` > '1487695796' AND `created` < '1487782196' ) 
//AND ( `message` = 'login failure' OR `message` = 'login success' OR `message` = 'log out' ) 
//ORDER BY `created` ASC

per verificare se la query generata da Codeigniter corrisponde al tuo SQL, puoi utilizzare:

echo $this->db->last_query(); // echos last query string