我在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;
}
我的问题是:是否有任何方法可以对其进行条件设置(知道我使用不同的搜索形式进行两个查询),或者我必须进行两个单独的查询?
感谢你们所有人?
当然可以。给函数添加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')
);
或者如果你想要连接,where set
$status = 'something';
$result = search('smith',
array('tManufacturer',
'nManufacturer=tReference.nManufacturer'),
array('nStatus', $status)
);
或者只需要where子句而不需要join
$status = 'something';
$result = search('smith', NULL, array('nStatus', $status) );