CodeIgniter Forums
Calling a Model from another Model - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Calling a Model from another Model (/showthread.php?tid=52350)



Calling a Model from another Model - El Forum - 06-07-2012

[eluser]Abishek R Srikaanth[/eluser]
Hi,

Can one model be called from within another model? Is this doable and is it good to use it this way?

I basically have a variable on a model, which is a foreign key object to another model itself. Can i load model 1 from model 2 to get the entity object onto a variable on model 2 (More like an POCO object)?

Thanks and Regards
Abishek R Srikaanth


Calling a Model from another Model - El Forum - 06-07-2012

[eluser]PhilTem[/eluser]
It can be done by simply addressing the model as you would do in a controller.

Code:
$this->my_other_model->one_method(); // Put this in any method of your first model

However, it is not best practice, since each model should only have knowledge about its corresponding table and not about anything else (that's why I think is pure MVC-understanding)
I tend to create a "wrapping" library as soon as I need to connect two or more tables/models.


Calling a Model from another Model - El Forum - 06-07-2012

[eluser]Abishek R Srikaanth[/eluser]
Should I load the model if it is already not loaded on the controller?
Will it throw an error if reload the model if it is already loaded in a Controller?