我在CodeIgniter 3上有一个简单的函数,它使用带有精炼变量的简单查询从数据库中提取一些数据:
function search($term){
$this->db->like('sReference',$term)
->or_like('nReference', $term)
->or_like('sSearch', $term)
->or_like('sSort', $term);
$query = $this->db->get('tReference');
$ret['rows'] = $query->result();
$ret['number'] = $query->num_rows();
return $ret;
}
此外,我需要对另一个搜索方法进行相同的查询,但只需添加两行,如下所示:
function search($term){
//Affichage de sproduits
$this->db->like('sReference',$term)
->or_like('nReference', $term)
->or_like('sSearch', $term)
->or_like('sSort', $term)
->join('tManufacturer','nManufacturer=tReference.nManufacturer')
->where('nStatus',$status);
$query = $this->db->get('tReference');
$ret['rows'] = $query->result();
$ret['number'] = $query->num_rows();
return $ret;
}
我的问题是:有没有办法对其作出规定(知道我对两个查询使用不同的搜索表单),或者我必须进行两次单独的查询?
感谢你们所有人?
答案 0 :(得分:2)
当然可以。在功能中添加2个参数,如果您愿意,可以使其非常灵活。
function search($term, $join=array(), $where=array()){
//Affichage de sproduits
$this->db->select('*')
->from('tReference');
->like('sReference',$term)
->or_like('nReference', $term)
->or_like('sSearch', $term)
->or_like('sSort', $term);
if ( is_array($join) && count($join) == 2 ) {
$this->db->join($join[0], $join[1]);
}
if ( is_array($where) && count($where) == 2 ) {
$this->db->where($where[0],$where[1]);
}
$query = $this->db->get();
$ret = array();
foreach ($query->result() as $row)
{
$ret['rows'][] = $row;
}
$ret['number'] = $query->num_rows();
return $ret;
}
现在称之为
$result = search('smith'); // just the ->like's
或者如果您想要设置联接
$result = search('smith',
array('tManufacturer',
'nManufacturer=tReference.nManufacturer')
);
或者如果你想要连接和设置
$status = 'something';
$result = search('smith',
array('tManufacturer',
'nManufacturer=tReference.nManufacturer'),
array('nStatus', $status)
);
或者如果您只想要where子句而不是连接
$status = 'something';
$result = search('smith', NULL, array('nStatus', $status) );