我正在condeigniter(新手)的一个项目上工作。我的项目包括使用不同过滤器(如类别、子类别、关键字、最低-最高价格等)的产品列表。我已经在自定义 php 中完成了数百次,在这里我为子句$where
中的所有条件设置了变量。where
例如
$where = '';
if($category != '')
{
$where .= " category = '$category'";
}
现在在 codeigniter 中我有多个参数,我可以在我的controller
throughuri segment
和 callmodel
函数中获取它们,并在那里传递所有参数run mysql query
。问题是我正在检查每个参数是否为空或已设置并相应地运行多个查询。例如。
if($category != '' && $subCategory != '')
{
//whole query here
}
else if($category == '' && $subCategory != '')
{
//whole query here
}
//and so on
我需要的是任何优化方式,因为我有连接(多个参数)。
我的示例条件和查询
if($subCat == '' && $vendor == '')
{
$cat = str_replace("-"," ",str_replace("-and-"," & ",$cat));
$this->db->select('listings.* ');
$this->db->from('listings');
$this->db->join('categories','categories.id = listings.category');
$this->db->where('categories.name',$cat);
$this->db->limit($perpage,$page);
$query = $this->db->get();
return $query->result();
}
else if($subCat == '' && $vendor != '')
{
$cat = str_replace("-"," ",str_replace("-and-"," & ",$cat));
$this->db->select('listings.* ');
$this->db->from('listings');
$this->db->join('categories','categories.id = listings.category');
$this->db->join('vendors','vendors.id = listings.programme');
$this->db->where('categories.name',$cat);
$this->db->where('vendors.name',$vendor);
$this->db->limit($perpage,$page);
$query = $this->db->get();
return $query->result();
}
else if($subCat != '' && $vendor == '')
{
$cat = str_replace("-"," ",str_replace("-and-"," & ",$cat));
$this->db->select('listings.* ');
$this->db->from('listings');
$this->db->join('categories','categories.id = listings.category');
$this->db->join('subcategories','subcategories.id = listings.subcategory');
$this->db->where('categories.name',$cat);
$this->db->where('subcategories.name',$subCat);
$this->db->limit($perpage,$page);
$query = $this->db->get();
return $query->result();
}
else
{
$cat = str_replace("-"," ",str_replace("-and-"," & ",$cat));
$subCat = str_replace("-"," ",str_replace("-and-"," & ",$subCat));
$vendor = str_replace("-"," ",str_replace("-and-"," & ",$vendor));
$this->db->select('listings.* ');
$this->db->from('listings');
$this->db->join('categories','categories.id = listings.category');
$this->db->join('subcategories','subcategories.id = listings.subcategory');
$this->db->join('vendors','vendors.id = listings.programme');
$this->db->where('categories.name',$cat);
$this->db->where('subcategories.name',$subCat);
$this->db->where('vendors.name',$vendor);
$this->db->limit($perpage,$page);
$query = $this->db->get();
return $query->result();
}