Conditional clauses using Codeigniter's Active Record

落花浮王杯 提交于 2019-12-11 06:32:36

问题


I have a function returning data based on the parameters passed. Basically, the queries change depending on the clauses.

if(1==$case) 
return select()->from('db')->where('x',$something)->where('y','fixed')...

else if(2==$case)
return select()->from('db')->where('x','fixed')->where('y',$something)...

Is there a better way of doing this?

Also, is it possible to have such a clause

...->where('category',*)

'*' to be replaced by a value or something which equates to "any".


回答1:


This type of queries is also called "dynamic queries" because you can combine the clauses in an easy way. Try this:

$query = $this->db->select()
    ->from('db');
if(1==$case) {
    $query->where('x',$something)
          ->where('y','fixed')
}
elseif (2==$case){
    $query->where('x','fixed')
          ->where('y',$something)
}
....
return $query->get();

Answering your second question, you can use:

$this->db->like('category', '%');



回答2:


You can do like this-

$where = array();

if(1==$case) 
 $where['x'] = $something;
 $where['y'] = 'fixed';

else if(2==$case)
 $where['x'] = $something;
 $where['y'] = 'fixed';

$this->db->where($where);
$this->db->get();



回答3:


You could have simplified it like this

if($case == 1){
    $this->db->where('x',$something)->where('y','fixed');
}else if($case == 2){
    $this->db->where('x','fixed')->where('y',$something)
}else{
    //no where clause
}
$query  =   $this->db->get('db_table');
return $query->result();


来源:https://stackoverflow.com/questions/15830793/conditional-clauses-using-codeigniters-active-record

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!