如何“保持”codeigniter activerecord状态

时间:2011-08-23 07:38:46

标签: php mysql codeigniter activerecord

在我的文章CURD列表中,我需要使用许多条件从数据库中获取文章,在获得符合条件的文章数量(无限制)后,我需要获得前10个符合条件的文章(限制10)。所以我想保持activerecord状态,如果可能,我不需要再写那些'where'。这是我的代码:

//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();

当我完成第一次查询时,活动记录状态为空,因此第二个查询错误。有没有办法保持这个?

3 个答案:

答案 0 :(得分:4)

我知道这是旧的,但我也在寻找一种方法来做到这一点,最终找到了内置的解决方案:

// 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();

答案 1 :(得分:0)

我相信你所采取的方法没有理由不起作用。例如,获取代码片段,整理并应用一些条件:

//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();

在我的测试应用程序中使用此功能,我会收集$num结果,然后收集$articles内的完整记录集。

答案 2 :(得分:0)

您可以使用简单的if子句

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();
    }
}

虽然我不确定是否有任何特定的codeigniter可以简化这一点,但这应该有效。