我正在从数据库中获取一些列表,并将其显示在分页屏幕中。但对于分页,我需要计算结果的总数。我正在使用Codeigniter和ActiveRecords。我的查询是这样的:
$query = $this->db->select('sum(amount) as sum')
->where(date_added between '$from' and '$to')
->group_by('date_added')
->get('my_table');
我需要运行这个查询,无论是否有获取值总数的限制,以及获取有限制的分页输出。现在我需要再次复制查询,并在有限制的情况下运行它。有没有其他方法可以将完整的查询对象复制到另一个变量并再次调用get?
您正在寻找活动记录缓存http://ellislab.com/codeigniter/user-guide/database/active_record.html#caching
public function cache_query() {
$this->db->start_cache();
$this->db->select('sum(amount) as sum')
->where(date_added between '$from' and '$to')
->group_by('date_added');
$this->db->stop_cache();
}
public function get_query() {
$this->build_query();
$query = $this->db->get('my_table');
$this->db->flush_cache();
}
public function count_query() {
$this->build_query();
$query = $this->db->count_all('my_table');
$this->db->flush_cache();
}
在选择有i限制的查询中使用SQL_CALC_FOUND_ROWS
的一种方法是,您还需要运行FOUND_ROWS()
,它将给出没有限制的所有行的计数
$query = $this->db->select('SQL_CALC_FOUND_ROWS sum(amount) as sum')
->where(date_added between '$from' and '$to')
->group_by('date_added')
->get('my_table')
->limit($perpage, $start);
然后你需要得到计数
$query = $this->db->query('SELECT FOUND_ROWS() AS `count`');
echo $query->row()->count;
FOUND_ROWS()
这样尝试在您的控制器中
function yourFunction()
{
$total_rows=$this->modal_name->function_name()->num_rows();
$this->db->limit(1,20); // set you limit here
$rows=$this->modal_name->function_name()->result_array();
}
你习惯于限制。$this->db->limit($limit,$start);