我正在使用Codeigniter 3.0.3。 我想用查询构建器构建一个查询,但是要在几个函数中拆分查询的构建。 例如:
class MyCart{
public function __construct() {
$this->db->select('A.id, A.title, A.price');
$this->db->from('articles A');
}
public function check_type($aTypeOfArticle){
$this->db->where("A.type=".$aTypeOfArticle);
}
public function check_price($aMaxPrice){
$this->db->where("A.price<=".$aMaxPrice);
}
public function get_result(){
$query = $this->db->get();
return $query->result();
}
}
但是当我尝试这个时,this->db->get()
返回false。
是否有可能使这项工作?
答案 0 :(得分:1)
这对你来说更有可能更好,
public function query()
{
$this->db->select('A.id, A.title, A.price');
$this->db->from('articles A');
if( check_type($aTypeOfArticle) )
{
$this->db->where("A.type=".$aTypeOfArticle);
}
if( check_price($aMaxPrice) )
{
$this->db->where("A.price<=".$aMaxPrice);
}
}
public function check_type($aTypeOfArticle){
// Do processing
return true or false;
}
public function check_price($aMaxPrice){
// Do Processing
return true or false;
}
在单个函数中构建查询,并调用另一个函数以获得处理结果。
答案 1 :(得分:0)
看看Method Chaining。您应该能够缓存from()
调用的返回值(例如在对象属性中),然后使用该值链接其上的其他方法。
答案 2 :(得分:0)
使用$this->db->start_cache()
和$this->db->stop_cache()
之类的Codeigniter查询构建器缓存。查看Documentation了解更多详细信息
class MyCart{
public function __construct() {
$this->db->start_cache();
$this->db->select('A.id, A.title, A.price');
$this->db->from('articles A');
}
public function check_type($aTypeOfArticle){
$this->db->where("A.type=".$aTypeOfArticle);
}
public function check_price($aMaxPrice){
$this->db->where("A.price<=".$aMaxPrice);
}
public function get_result(){
$this->db->stop_cache();
$query = $this->db->get();
return $query->result();
$this->db->flush_cache();
}
}