[英]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.