how to "keep" codeigniter activerecord status
In my article CURD list, I need to get articles from database using many conditions, after get number of eligible articles(no limit), I need to get first 10 eligible articles (limit 10). So I want to keep the activerecord status, if it's possible, I don't need to write those 'where' again. Here are my code:
//select num
$this->db->select('count(*) as num')
//conditions
$this->db->where/or_where/having/order_by//many conditions...
//get num
$num = $this->db->get('articles')->first_row()->num;
//get articles
$this->db->limit(10);
$articles = $this->db->get('articles')->result();
When I finished my first query, the active record status is empty, so the second query开发者_Python百科 is wrong. Is there any way to keep that?
I know this is old, but I was also looking for a way to do this, eventually found the built in solution:
// Start of the query you want to re-use
$this->db->start_cache();
//select num
$this->db->select('count(*) as num')
//conditions
$this->db->where/or_where/having/order_by//many conditions...
// End of the query you want to re-use
$this->db->stop_cache();
//get num
$num = $this->db->get('articles')->first_row()->num;
//get articles
$this->db->limit(10);
$articles = $this->db->get('articles')->result();
// Clear the saved query
$this->db->flush_cache();
I believe there is no reason why the approach you are taking shouldn't work. For instance taking your code snippet, tidying up and applying some conditions to it:
//select num
$this->db->select('count(*) as num');
//conditions
$this->db->where(array('title' => 'Hello world'));
//get num
$num = $this->db->get('articles')->first_row()->num;
//get articles
$this->db->limit(10);
$articles = $this->db->get('articles')->result();
echo "!".$num."!<br />";
print_r($articles);
exit();
Using this within my test application I gather the $num
result and then a full recordset within $articles
.
You could just use a simple if clause
function get_data($type) {
//select num
$this->db->select('count(*) as num')
//conditions
$this->db->where/or_where/having/order_by//many conditions...
//get num
if($type == 'count')
return $this->db->get('articles')->first_row()->num;
//get articles
if($type == 'articles') {
$this->db->limit(10);
return $this->db->get('articles')->result();
}
}
Although I am not sure if there is anything specific for codeigniter that can simplify this, this should work.
精彩评论