2011-08-23 2 views
2

내 기사 CURD 목록에서 여러 조건을 사용하여 데이터베이스에서 기사를 가져와야합니다. 해당 기사의 수 (제한 없음)를 얻은 후 처음 10 개의 적합한 기사 (한도 10). 그래서 activerecord 상태를 유지하고 싶습니다. 가능한 경우 다시 'where'를 쓸 필요가 없습니다. 여기에 내 코드는 다음과 같습니다."codeigniter"activerecord 상태를 유지하는 방법

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

첫 번째 쿼리를 완료하면 활성 레코드 상태가 비어 있으므로 두 번째 쿼리가 잘못되었습니다. 그걸 지킬 방법이 있습니까?

답변

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 내에서 다음 전체 레코드를 수집합니다. 나는이 문제를 단순화 할 수 CodeIgniter의 특정 무엇이든이있는 경우,이 작업을해야 확실하지 오전하지만

+0

은 내가 사용하는 $ this-> DB-> last_query() 거기 참조 첫 번째 쿼리의 조건이지만 두 번째 쿼리의 조건은 없습니다. CI가 모호한 쿼리를 피하기 위해 그러한 조건을 명확하게했기 때문에 그것이라고 생각했습니다. 나는 현재 CI 2.0.2를 사용하고 있습니다. – missingcat92

0

당신은

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

절 경우 간단한을 사용할 수 있습니다.

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(); 
관련 문제