首页 > 解决方案 > MySQL get_where 与 Codeigniter 中的 If 条件

问题描述

我的模型中有以下功能可以明智地过滤官员记录。该功能工作正常。

public function getOfficer()
    {
        $q = $this->db->order_by('last_name','ASC')->get_where('tbl_officer', array('status' => '1', 'usr' =>$this->session->userdata('id_user')));    
        if ($q->num_rows() > 0) {
            return $q->result();
        }
        return false;
    }

此外,我只想过滤会话中用户 = 4 的官员记录,通过 p_code->8,10 和 24

If 函数如下:

if($usr == 4)
        {
        $this->datatables->where('tbl_officer.p_code', 8)->or_where('tbl_officer.p_code', 10)->or_where('tbl_officer.p_code', 24);

        } else {
        $this->datatables->where('tbl_officer.usr', $usr);
    }

如何将此 If 条件包含到我上面提到的模型函数中?有什么可以改变的?任何人都可以帮忙吗?

标签: phpmysqlcodeigniter

解决方案


只需要改变查询写法

public function getOfficer()
 {
     $usr = $this->session->userdata('id_user');
     $userArray = array(8,10,24);
     $this->db->select('*');
     $this->db->from('tbl_officer');
     if($usr == 4){
        $this->db->where_in('usr',$userArray );
     }else{
        $this->db->where('usr',$usr);
     }
     $q = $this->db->get();
     if ($q->num_rows() > 0) {
        return $q->result();
     }
     return false;
}


推荐阅读