Welcome Guest, Not a member yet? Register   Sign In
Newbie question : can I load a model within a model ?
#1

[eluser]Unknown[/eluser]
Hi

I'm trying CodeIgniter on a small project.
I need to make an object by mixing datas from several tables. I've made a Model (ex : model1, model2, model3) for each table and I would like to use model2 and model3 in model1.
Is it possible ?
Is there another approach to do that ?

Thanks in advance,

Swdes
#2

[eluser]gtech[/eluser]
yes, if loaded in models constructor.. if outside the constructor you have to get the CI object instance, there was a discussion on this a while back i'll dig out the thread and post it here
#3

[eluser]gtech[/eluser]
[url="http://ellislab.com/forums/viewthread/63953"](see this thread)[/url]

1)you will find my simple example of loading in the constructor.

2)you will find mpress's rather clever solution of putting:
Code:
$this->_ci_assign_to_models();
in the model method of loader.php, which enables you to load a model in the normal way outside the constructor.

3)you will find codeofficers nifty method of getting the CI (Code Igniter) object so you can load a model outside the constructor:

[quote author="CodeOfficer" date="1193827453"]this works great for me:
Code:
class MyModel extends Model
{
    private $CI;
    
    function MyModel()
    {
        parent::Model();
        $this->CI =& get_instance();    
    }
    
    function whatever()
    {
        $this->CI->load->model('model1');    
        $this->CI->model1->method1();
    }
    
    function woot()
    {
        $this->CI->load->model('model2');    
        $this->CI->model2->method2();    
    }
}
[/quote]


so you have three valid ways of doing it Smile




Theme © iAndrew 2016 - Forum software by © MyBB