2013-09-25 65 views
0

我在控制器中做了一個查詢,但是讓我注意到我應該在模型中進行查詢。如何在模型中運行查詢並在控制器中加載?

這是我在控制器

$this->db->where('page', 'your-secret-skill'); 
    $this->data['articles'] = $this->article_m->get(); 

的代碼,這是get方法我在覈心模式:

public function get($id = NULL, $single = FALSE){ 

    if ($id != NULL) { 
     $filter = $this->_primary_filter; 
     $id = $filter($id); 
     $this->db->where($this->_primary_key, $id); 
     $method = 'row'; 
    } 
    elseif($single == TRUE) { 
     $method = 'row'; 
    } 
    else { 
     $method = 'result'; 
    } 

    if (!count($this->db->ar_orderby)) { 
     $this->db->order_by($this->_order_by); 
    } 
    return $this->db->get($this->_table_name)->$method(); 
} 

我怎麼會去這樣做查詢在文章模型中加載控制器?

+1

大聲笑,關於閱讀CI文檔 –

+0

的第一線我一直在它是什麼,但沒有爲我工作至今 – tvieira

回答

1

你應該繼承與本刊模型CI_Model和它,你可以寫你的查詢爲:

class Articles_m extends CI_Model 
{ 
    function __construct() 
    { 
      parent::__construct(); 
      $this->table_name = 'articles'; 
    } 


    public function get() 
    { 
    $this->db->where('page', 'your-secret-skill'); 
    $query = $this->db->get($this->table_name); 
    return $query->result(); 
    } 

} 

,然後在你的控制器:

$this->data['articles'] = $this->article_m->get(); 
+0

我得到一個服務器錯誤,並且CI文件中的日誌/不會給我指示器發生了什麼事情:\ – tvieira

+0

然後是什麼錯誤?你是否自動加載數據庫? –

+0

沒關係,我有一個語法錯誤(如99%的時代笑)它現在的作品 – tvieira

0

從控制器首先刪除此行:

$this->db->where('page', 'your-secret-skill'); 

改爲發送your-secret-skill作爲參數傳遞給你R型功能:

$where = array('page', 'your-secret-skill'); 
$this->data['articles'] = $this->article_m->get('','',$where); 

在你的模型:

public function get($id = NULL, $single = FALSE, $where = array){ 
    if(isset($where) && is_array($where)){ 
     $this->db->where($where); 
    } 
} 
相關問題