Welcome Guest, Not a member yet? Register   Sign In
load model from within model

Hi All,

Is it possible to load a model from within a model? And if yes how does the code look like?

If i write the following

$username = $this->users_model->get_username_by_user_id($user_id);

it will fail with this error message

Quote:A PHP Error was encountered

Severity: Notice

Message: Undefined property: Favorites_model::$users_model

Filename: models/favorites_model.php

Line Number: 46

So either it is not possible to access a model from within a model, or there is a different way from loading a model from within a model?

Can anyone point me in the right direction?


Yes, it's possible to load a model from within a model.

On you model class, in the constructor function implement:

class users_model extends Model {

    function users_model() {
        $this->obj =& get_instance();


This code is working in CodeIgniter as I've tried it when I developed a similar model.

Thank you, devpedia,

I assume, calls like


can be in any method of the model?

Best regards,

Yes it can be.

devpedia or anybody else,

Maybe u know the answer about a very similar problem:
How to access a config item from within the same config file...

$config['home_img_tag'] = 'some html' . $this->config->item('base_url') . 'some html';

The above does not seem to work...


Actually it is obvious:

$config['home_img_tag'] = 'some html' . $config('base_url') . 'some html';


WRT models in models you can also

autoload a model

and it will be available in any other models. added in CI 1.6

Why do you have to get an instance of CI, when you're extending a Model?

Just like in a constructor, when you're extending it.. you don't need to get an instance of CI, you just go for it..

But when you're loading a model within a model, why would you need to get an instance, as that's extending model?

it's a quirk in the way that CI is set up. that is one of the reasons models were added to autoload routine in CI 1.6.

Theme © iAndrew 2016 - Forum software by © MyBB