Codeigniter model error

2019-04-17 08:20发布

问题:

I created a new model class as my_model.php inside /models folder, and a function inside it to load all elements:

function get_all(){
    $query = $this->db->get('test'); //test is my table 
   return $query->result();
}

In the controller, I instantiated the class and called the method;

$this->load->model('my_model');
$res = $this->my_model->get_all();

But, this throws me error saying:

Fatal error: Call to a member function get() on a non-object in /var/www/testapp/application/models/my_model.php on line 7

This line 7 points to the portion of the code where I have used $this->db. I tried to see the value of $db but I think it is magic accessor __get and __set, so I could not see the value of this property before calling that method.

I tried googling for several other cases but none of them match my scenarios and rather none of them could solve my problem.

回答1:

You have to load the Database first

$this->load->database();

So, all code:

function get_all(){
    $this->load->database();
    $query = $this->db->get('test'); //test is my table 
    return $query->result();
}

Or, load database in your __construct method.

Or, IMO, It's better to autoload database by changing application/config/autoload.php, example is below.

$autoload['libraries'] = array('database','form_validation'); //form_validation is for example only


回答2:

In CodeIgniter, you should load database model before you use it. Use $this->load->database(); to load database model.



回答3:

Your error is actually quite simple:

return $query->result;

Should be:

return $query->result();

Sometimes the line number reported by a PHP error isn't exactly the one you think it is, the parser is just doing it's best and reporting where it found an error.

There's one more issue:

$res = $this->my_model->getAll();

Should be:

$res = $this->my_model->get_all();

You have called your own function by the wrong name.