CodeIgniter模型不起作用


CodeIgniter Models Don't Work

我需要从数据库中读取一些数据控制器是

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

问题在哪里,我应该如何解决它?特别感谢您的关注

我100%确定你没有在你的自动加载中添加数据库。

请进入你的配置文件夹,然后打开autoload.php,搜索一行自动装载美元[‘库’]。

添加:

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

或者你可以这样做:

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

看起来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 ;)
        }
        //..
    }

此外,在控制器中自动加载模型可能被认为是"不好的做法",因为及时加载会提高性能(即使平均几乎可以忽略不计)。所以,我建议在你需要的地方加载你的模块,即

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

并从控制器中完全删除__construct(),如果您出于其他原因不使用它。