[英]Codeigniter: Better way to select db?
這是我從SQL數據庫獲取內容的功能...
有沒有更優雅的方法可以做到這一點?
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)...
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');
}
@Steven結果的優化版本(對於初學者而言可能更復雜)。 這假定您不超出數組索引引用的范圍,否則將出錯。
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');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.