Welcome Guest, Not a member yet? Register   Sign In
models within models
#1

[eluser]Unknown[/eluser]
CI doesn't seem to allow loading a model within a model.

I want model1 to set the instance of model2 as a member variable.

If I load both models in the controller and set the model1->var = $this->model2, things seem to work, but a var_dump of the $this->model1 creates an infinite loop.

I haven't dug into the framework to figure this out, but has anyone else ran into this?

Isaac Vetter
#2

[eluser]ejangi[/eluser]
Loading Models into Models kinda breaks the whole MVC thing (cause models shouldn't know anything about anything else), but you just need to do this:
Code:
Class MyModel extends Model {

    function MyModel()
    {
        $this->CI =& get_instance();
        $this->CI->load->model('my_other_model');
        // And then use it like so:
        return $this->CI->my_other_model->do_whatever();
    }

}
#3

[eluser]gtech[/eluser]
If you load the model inside the constructor you can load it in the normal way, outside the constructor you need to use ucantblamem's method. This has come up in previous posts before so you can search the forums, If it breaks the MVC rules then I slap myself on the wrists as I do it frequently, a cascading delete would be an example of when I load other models (e.g. when I delete users I also need to delete contents) and it seems silly just to rewrite other models methods.

Code:
class Contentsdb extends Model
{
  /**
   * The Initialisation method
   */
  function contentsdb()
  {
    parent::Model();
    $this->load->model('itemsdb');
  }
#4

[eluser]esra[/eluser]
I'm working from my laptop away from home tonight without a host and could not try this, but you might try a couple of experiments.

Experiment 1) Try placing two model classes in the same model file, load the model in a controller like normal, then try to access both models.

-----------
Experiment 2) Extend one model from another. In the extended model's constructor, set the parent to the Model class rather than the parent class. Then try to access both models.




Theme © iAndrew 2016 - Forum software by © MyBB