我面临的一个问题是有许多查询具有相似的选择语句但不同的连接/位置语句。
下面是我正在通过 CodeIgniter 处理的代码示例。我通常做的是创建一个函数 get(),它接受一组随机键/值。根据传递的键/值,它将生成并运行适当的查询。现在,我想知道这是一种很好的做事方式吗?因为如你所见,这个函数变得越来越复杂。最初,我有一堆函数,例如 get_all()、get_only_lessons() 等,但是不得不用一两行不同的行重复同一组代码变得有点烦人。
我的问题是处理这个问题的最佳方法是什么。
function get($param = NULL)
{
/*
SELECT m.id AS id, CAST(m.order_number AS SIGNED) AS order_number, m.name AS name, m.permalink as permalink,
m.suplesson_id as suplesson_id, CAST(sm.order_number AS SIGNED) AS suplesson_order_number
FROM lessons m
JOIN courses c ON m.course_id = c.id
LEFT JOIN lessons sm ON m.suplesson_id = sm.id
WHERE [various]
*/
$select = 'm.id AS id, CAST(m.order_number AS SIGNED) AS order_number, m.name AS name, m.permalink as permalink, ';
$select .= ' m.suplesson_id as suplesson_id';
if (isset($param['id']) || isset($param['suplesson_order_number']) || isset($param['permalink']))
$select .= ', CAST(sm.order_number AS SIGNED) AS suplesson_order_number ';
$this->db->select($select);
$this->db->from($this->table_name.' m');
$this->db->join($this->courses_table_name.' c', 'm.course_id = c.id');
if (isset($param['id']) || isset($param['suplesson_order_number']) || isset($param['permalink']))
$this->db->join($this->table_name.' sm', 'm.suplesson_id = sm.id', 'left');
// where clauses
if (isset($param['course_id']))
$this->db->where(array('c.id' => $param['course_id']));
if (isset($param['id']))
$this->db->where(array('m.id' => $param['id']));
if (isset($param['order_number']))
$this->db->where(array('m.order_number' => $param['order_number']));
if (isset($param['permalink']))
$this->db->like('m.permalink', $param['permalink'], 'none');
if (isset($param['suplesson_id']))
$this->db->where(array('m.suplesson_id' => $param['suplesson_id']));
if (isset($param['suplesson_order_number']))
$this->db->where(array('sm.order_number' => $param['suplesson_order_number']));
if (isset($param['NULL']))
$this->db->where('m.'.$param['NULL'].' IS NULL');
if (isset($param['NOT NULL']))
$this->db->where('m.'.$param['NOT NULL'].' IS NOT NULL');
$this->db->order_by('order_number');
// filter based on num_rows/offset
if (isset($param['id']) || isset($param['permalink']))
$this->db->limit(1);
if (isset($param['num_rows']) && isset($param['offset']))
$this->db->limit($param['num_rows'], $param['offset']);
$query = $this->db->get();
// return row if expecting 1 result
if (isset($param['id']) || isset($param['suplesson_order_number']) || isset($param['permalink']))
return ($query->num_rows() == 1) ? $query->row_array() : NULL;
return ($query->num_rows() > 0) ? $query->result_array() : NULL;
}