【问题标题】:Conditional clauses using Codeigniter's Active Record使用 Codeigniter Active Record 的条件子句
【发布时间】:2013-04-05 09:49:34
【问题描述】:

我有一个函数根据传递的参数返回数据。 基本上,查询会根据子句而变化。

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)...

有没有更好的方法来做到这一点?

还有,有没有可能有这样的条款

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

'*' 被一个值或等同于“any”的东西替换。

【问题讨论】:

    标签: php codeigniter activerecord


    【解决方案1】:

    这种类型的查询也称为“动态查询”,因为您可以轻松地组合子句。试试这个:

    $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();
    

    回答你的第二个问题,你可以使用:

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

    【讨论】:

      【解决方案2】:

      你可以这样做-

      $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】:

        你可以像这样简化它

        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();
        

        【讨论】:

          猜你喜欢
          • 2013-04-11
          • 2015-09-17
          • 1970-01-01
          • 1970-01-01
          • 2017-11-30
          • 1970-01-01
          • 1970-01-01
          • 2015-07-31
          • 2014-12-24
          相关资源
          最近更新 更多