2011-10-13 61 views
-1

我需要從數據庫中讀取一些數據 我控制器CodeIgniter的模型不工作

class Pro_ajax extends CI_Controller{ 
    public function _construct() { parent::_construct(); 
     $this->load->model('ajax_model'); 
    } 
    public function _remap($method,$param = array()) 
    { 
     if ($method == 'user_search') 
     { 
      $this->user_search($param[0]); 
     } 
    } 
    private function user_search($text = '') 
    { 
     $result = $this->ajax_model->ajax_user_search($text); 
     $count = count($result); 
     $data = array(); 
     for ($i = 0;$i < $count AND $i < 5;$i++) 
     { 
      $data[$i][0] = $result->id; 
      $data[$i][1] = $result->firstname.' '.$result->lastname; 
     } 
     echo (json_encode($data)); 
    } 
}
和我的模型是:

class Ajax_model extends CI_Model{ 
    public function __construct() { 
     parent::__construct(); 
    } 
    public function ajax_user_search($text = '') 
    { 
     $this->db->flush_cache(); 
     $this->db->limit(5); 
     $this->db->or_like('firstname',$text); 
     $this->db->or_like('lastname',$text); 
     $this->db->or_like('alias',$text); 
     $this->db->or_like('username',$text); 

     $query = $this->db->get('user_store_table'); 
     var_dump($this->db->last_query()); 
     return $query->result(); 
    } 
} 

,但它不工作和回聲以下:


A PHP Error was encountered 

Severity: Notice 

Message: Undefined property: Pro_ajax::$db 

Filename: core/Model.php 

Line Number: 50

問題在哪裏,我該如何解決? 特別感謝您的關注

+1

你有沒有自動加載你的數據庫?在自動加載文件在配置? – AlphaMale

+0

沒有,CI_Model不會自行做呢?我伸出從中 –

+0

您正在使用哪個版本的CodeIgniter我的模型?你的代碼有點混亂。你可以請發佈完整的代碼,因爲我無法在任何地方看到Pro_ajax。 – AlphaMale

回答

7

我相信你沒有在你的自動加載數據庫添加100%。

請轉到您的配置文件夾,然後打開autoload.php並搜索具有 $ autoload ['libraries']的行。

補充一點:

$autoload['libraries'] = array('database'); 

,或者你可以這樣做:

class Ajax_model extends CI_Model{ 
     public function __construct() { 
      parent::__construct(); 
      $this->load->database(); 
     } 

    } 

希望這有助於。

+1

+1的直覺:) –

+0

alphamale是個聰明人:-)不錯ANS .... – chhameed

+0

它的工作非常感謝你 – RaviPatidar

3

看起來像CI正在將$ this解釋爲控制器的實例而不是數據庫對象......正如@AlphaMale巧妙指出的那樣,您是否已經裝載了它?

class Ajax_model extends CI_Model{ 
     public function __construct() { 
      parent::__construct(); 
      $this->load->database(); //No, database doesn't autoload by default 
      //this is something which I strongly suggest to do in the config/autoload.php file..you're going to use it a lot in Models ;) 
     } 
     //.. 
    } 

此外,控制器自動加載一個模型可以被認爲是「不好的做法」,因爲加載剛剛在時間的增加(即使幾乎可以忽略量平均)perforamnce。 所以,我建議裝在你需要它的模塊權,即

private function user_search($text = '') 
{ 
    $this->load->model('ajax_model'); 
} 

,並刪除altogheter從控制器__construct(),如果你不使用它的其他原因。

+0

+1爲澄清。 – AlphaMale