2017-01-22 44 views
0

在笨3.1.3我在應用/核心擴展CI_Model/MY_Model.php:

class MY_Model extends CI_Model { 

    public function __construct($id = NULL) { 
     parent::__construct(); 
     $this->load($id); 
    } 

    public function load($id) { 
     $this->db->where('id', $id); 
     $this->db->limit(1); 
     $query = $this->db->query($this->_table); 
     if ($row = $query->result()) { 
      // @todo Process results 
     } 
     // Free the resources. 
     $query->free_result(); 
    } 

} 

我User_model看起來是這樣的:

class User_model extends MY_Model { 

    public function __construct($id = NULL) { 
     parent::__construct($id); 
    } 

} 

我也延長了應用程序/核心/ MY_Controller中的CI_Controller如下:

class MY_Controller extends CI_Controller { 

    public function __construct() { 
     parent::__construct(); 
     $this->load->model('User_model'); 
    } 
} 

我自動加載數據庫連接通貨膨脹/配置/ autoload.php爲:

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

不加載User_model在控制器我能夠運行遷移,所以數據庫連接配置正確。但是當我添加$ this-> load-> model('User_model')時,出現錯誤「Undefined property:User_model :: $ db」。

如果我讓User_model擴展CI_Model,它運行時沒有錯誤,並且在主頁的控制器中有一個var_dump,它顯示數據庫是正確自動加載的。但是,只要我把MY_Model置於中間,數據庫類在模型中未定義,並且模型中的$ this-> load返回NULL,所以看起來模型沒有正確構造。

我只能想象這是一個非常小的錯誤,但我一直盯着它幾個小時,在幾次休息之間,我只是沒有看到它。其他人能幫助我嗎?

回答

0

從控制器,可以說A_controller

$this->load->library('MyLib'); 

MyLib中,我原來的問題是,該塊

$ci = &get_instance(); 
    $ci->load->model('my_model'); 

    $this->active_model = $ci->my_model; 

然後奇蹟來,當它成爲

$ci = &get_instance(); 
    $ci->load->model('my_model'); 
    $ci->my_model->db = & $ci->db; 

    $this->basic_model = $ci->my_model; 

當CI加載模型$ db屬性與CI一起。 因此,當您在模型中調用$ this-> db時,這意味着您希望「my_model」擁有該屬性,對嗎? 我所做的只是將屬性從CI鏈接到my_model!