djeetee
djeetee

Reputation: 1837

Loading and using a codeigniter model from another model

Fellow coders, using codeigniter 1.7.3 can I load a model from the code of another model? I have read many posts theoretical and practical but none gave a final answer.

I have a model that has a function in which i would like to perform an operation on another model. the code is like this:

1: $this->load->model('decision_model');
2: $this->decision_model->hello_decision();  

line 1 works. line 2 fails as follows:

A PHP Error was encountered
Severity: Notice
Message: Undefined property: Account_model::$decision_model
Filename: models/account_model.php

I have tried creating simple dumb models, changed function names, giving the model an alias when loading it, etc... no luck

So, theory aside, is this doable?

thanks in advance.

Upvotes: 14

Views: 33765

Answers (5)

Marcos Riso
Marcos Riso

Reputation: 1

I would create a CodeIgniter Library, and make the library make the model operation and then return it to the current model. I think this approach is more clean.

Upvotes: 0

Gary Rogers
Gary Rogers

Reputation: 405

You can also add a private $_ci; class variable, and initialize it in your constructor.

public function __construct($input=null)
{
    $this->_ci =& get_instance();

    if ( $input != null && is_array($input) ) {
         $this->populate($input);
    }
}

Then it'll be available to any function you're working with, no need to get_instance() all over the place.

Upvotes: 1

phirschybar
phirschybar

Reputation: 8579

In CI 2.0 you can just call one model directly from another.

Upvotes: 10

Teej
Teej

Reputation: 12873

You can do it like this:

class User_model extends Model
{
    function get_something()
    {
         $CI =& get_instance();
         $CI->load->model('profile_model');
         return $CI->profile_model->get_another_thing();
    }
}

Upvotes: 20

user516322
user516322

Reputation: 338

Try this:

$this->load->model('decision_model');
$CI =& get_instance();
$CI->decision_model->hello_decision(); 

Upvotes: 1

Related Questions