2010-01-16 1 views
0

이것은 SQL 데이터베이스에서 물건을 얻는 나의 함수입니다 ...Codeigniter : db를 선택하는 더 나은 방법은?

더 우아한 방법이 있나요?

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'); 
}