在添加进一步限制语句CodeIgniter之前计算行数?

Dan*_*nny 7 php database codeigniter

我遇到了一个问题......

我有一堆像这样的陈述......

$this->db->where('Pool', "1");
$this->db->where('Bedrooms >=', "3");
Run Code Online (Sandbox Code Playgroud)

然后是限制声明

$this->db->limit($limit, $offset);
Run Code Online (Sandbox Code Playgroud)

最后我得到了声明

$query = $this->db->get('table-name');
Run Code Online (Sandbox Code Playgroud)

我的问题是我需要在我的限制语句之前计算结果,以获得没有限制的总行数.所以我尝试了这个..

$this->db->where('Pool', "1");
$this->db->where('Bedrooms >=', "3");

$num_rows = $this->db->count_all_results();

$this->db->limit($limit, $offset);
$query = $this->db->get('table-name');
Run Code Online (Sandbox Code Playgroud)

这将使用where语句对我的行进行计数.但是,get语句现在获取没有先前where语句工作的记录.

它是不可见的,但有大量的代码处理更多的语句,并抓住网址中的东西,所以我宁愿不执行两次数据检索,以解决这个问题...

干杯!

Kha*_*han 13

我知道这是一个老问题,但我只是碰到了这个问题,并有不同的解决方案上来.

我们的想法是在限制和偏移之前获取db类的副本.

$this->db->where('Pool', "1");
$this->db->where('Bedrooms >=', "3");

//here we use the clone command to create a shallow copy of the object
$tempdb = clone $this->db;
//now we run the count method on this copy
$num_rows = $tempdb->from('table-name')->count_all_results();

$this->db->limit($limit, $offset);
$query = $this->db->get('table-name');
Run Code Online (Sandbox Code Playgroud)


小智 7

我知道这是一个老问题,但我发现了一个很简单的解决方案。

//do your select, from and where
$this->db->select('your selects');
$this->db->from('your table');

$this->db->where('your where');

//get the filtered rows count
//the trick is the first empty parameter and second false parameter
$filtered_count = $this->db->count_all_results('', false);

//limit your results and get the rows
$this->db->limit($length, $start);
$results = $this->db->get()->result_array();
Run Code Online (Sandbox Code Playgroud)

希望对别人有帮助


Wah*_*nto 5

$get_data = $this->your_model->get_data();
$data     = $get_data['data'];
$count    = $get_data['count'];
Run Code Online (Sandbox Code Playgroud)

模型

function get_data($limit = 10, $offset= 0)
{
    $table = 'table-name';
    $where = array('Pool' => 1, 'Beedrooms >=' 3);

    $return['data']  = $this->db->from($table)->where($where)->limit($limit, $offset)->get();
    $return['count'] = $this->db->from($table)->where($where)->count_all_results();

    return $return;
}
Run Code Online (Sandbox Code Playgroud)


cod*_*ror 5

    $this->db->select('*');
    $this->db->from('users');
    $this->db->where('active',$status);

    //open1 here we copy $this->db in to tempdb and apply 
    //count_all_results() function on to this tempdb
    $tempdb = clone $this->db;
    $num_results= $tempdb->count_all_results();   

    // now applying limit and will get actual result 
    $this->db->limit(10);

    $this->db->get();
    $query = $this->db->last_query();
    $res = $this->db->query($query);        

    $data_array = array('num_results' => $num_results, 'results' => $res->result() );
    return $data_array;
Run Code Online (Sandbox Code Playgroud)