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

[eluser]mradlmaier[/eluser]
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

Code:
$this->load->model('users_model');
$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?

Michael
#2

[eluser]bitist[/eluser]
Yes, it's possible to load a model from within a model.

On you model class, in the constructor function implement:

Code:
class users_model extends Model {

    function users_model() {
        parent::Model();
        $this->obj =& get_instance();
        $this->obj->load->model('another_model');
        $this->obj->another_model->function_of_another_model();
    }

}

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

[eluser]mradlmaier[/eluser]
Thank you, devpedia,

I assume, calls like

Code:
$this->obj->another_model->function_of_another_model();

can be in any method of the model?

Best regards,
Michael
#4

[eluser]bitist[/eluser]
Yes it can be.
#5

[eluser]mradlmaier[/eluser]
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...

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



The above does not seem to work...

Michael
#6

[eluser]mradlmaier[/eluser]
Actually it is obvious:

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

Michael
#7

[eluser]sophistry[/eluser]
WRT models in models you can also

autoload a model

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

[eluser]Dentafrice[/eluser]
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?
#9

[eluser]sophistry[/eluser]
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