2010-01-16 23 views
0

這是我的功能從SQL分貝獲取的東西...Codeigniter:更好的方式來選擇數據庫?

有沒有更優雅的方式來做到這一點?

function getResults_1($id) 
{ 
    $this->db->select(array("a_1","a_2"))->from('Survey'); 
    $this->db->where('user_id', $id); 

    return $this->db->get(); 
} 
function getResults_2($id) 
{ 
    $this->db->select(array("a_6","a_8","a_13","a_14"))->from('Survey'); 
    $this->db->where('user_id', $id); 

    return $this->db->get(); 
} 
and so on... (to 5)... 

回答

1

@史蒂芬的結果更優化的(或許對於初學者用戶更令人費解的)版本。這假設你不會超出數組索引引用的範圍,否則會出錯。

function get_results($id, $method) { 
    $select_cols = array(1 => array('a_1','a_2'), 
         2 => array('a_6','a_8','a_13','a_14')); 
    return $this->db->select($select_cols[$method]) 
        ->where('user_id', $id) 
        ->get('Survey'); 
} 
2
function get_results($id, $method) { 
    switch($method) { 
     case 1: $select = array('a_1','a_2'); break; 
     case 2: $select = array('a_6','a_8','a_13','a_14'); break; 
     default: $select = false; 
    } 

    if($select) $this->db->select($select); 
    $this->db->where('user_id',$id); 

    return $this->db->get('Survey'); 
} 
相關問題