开发者

Codeigniter Undefined property: xxxx_model::$db only from Model

First the Model class:

    class Xxxx_model extends Model
    {
      function XxxxModel()
      {
        parent::Model();
        $this->load->database();
      }

      function isInDatabase()
      {
        // Please ignore the sql query, it's just to show some random sql code with results
11.      $result = $this->db->query('SELECT * FROM someTable WHERE ...');
        $numberOfRows = $result->num_rows();
        ... 
        return $test;
      }
    }

Now the controller:

function someLogic()
{
  $this->load->model('xxxx_Model', 'xxxxModel'); // not necessary to specify
  $this->xxxxModel->isInDatabase();
}

When I run this I get the error:

Severity: Notice  --> Undefined property: Xxxx_model::$db .../xxxx_model.php line 11

I have no idea why this is. If I put the db code in the controller it seems to work, it's only with this setup in the model that it fails.开发者_如何学JAVA I can't for the life of me figure out where the code is astray...


You have to load the db library first. In autoload.php add below code,

$autoload[‘libraries’] = array(‘database’);


add library 'datatabase' to autoload.

/application/config/autoload.php

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

Propably you're started new project, like me ;-)


To add to atno's answer:

class Xxxx_model extends Model
{
  function XxxxModel() //<--- does not match model name Xxxx_model
  {
    parent::Model();
    $this->load->database();
  }

Basically, you are not constructing the class or the parent class Model. If you are on PHP5, you may use __construct(), otherwise you must match the class name exactly, regardless of what alias you load it with in your controller. Example:

class Xxxx_model extends Model
{
  function __construct()
  {
    parent::__construct(); // construct the Model class
  }
}

I may be mistaken (haven't used 1.x in a while), but if you construct the Model class, there's no need to load the database if you are using the default connection settings in config/database.php, it should already be loaded for you.


If function XxxxModel() isn't your constructor, you're not loading the database by calling $this->xxxxModel->isInDatabase();

Try autoloading the database library from within autoload.php, or create a proper constructor in your model.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜