CodeIgniter Forums
Can a model use another model? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forum-23.html)
+--- Thread: Can a model use another model? (/thread-26442.html)



Can a model use another model? - El Forum - 01-13-2010

[eluser]HugoA[/eluser]
I have a model class that make all the data base operations, but i want that model to use another class and put all the data from the data base in some variables, then, i just send to the controller an array of mi object.

for example:

this is the class

Code:
<?php

class Person extends Model{
    
    private $name;
    private $lastname;
    private $password;
    
    
    public function getName()
    {
        return $this->name;
    }
    
    function setName($data)
    {
        $this->name = $data;
    }
    
    public function getLastname()
    {
        return $this->lastname;
    }
    
    public function setLastname($data)
    {
        $this->lastname = $data;
    }
    
    public function getPassword()
    {
        return $this->password;
    }
    
    public function setPassword($data)
    {
        $this->password = $data;
    }
    
}

?>

and this is the model
Code:
<?php

class Formulario_model extends Model{
    
    function obtener_usuario()
    {
        $this->db->where('idpersona','1');
        $query = $this->db->get('persona');
        if($query->num_rows() > 0){
            foreach($query->result() as $row){
                $this->load->model('person');
                $this->person->setName($row->name);
            }
            return $data;
        }
    }
    
}

?>

if i do this i get this error

Fatal error: Call to a member function setName() on a non-object in C:\Aplicaciones\formulario\system\application\models\formulario_model.php on line 13

how can i solve this?
thanks


Can a model use another model? - El Forum - 01-13-2010

[eluser]Colin Williams[/eluser]
Because the model has not been previously loaded, it's not yet a part of the CI object, so it is never copied to your current model. You'll need to go through the CI object to do so

Code:
$ci =& get_instance();
$ci->load->model('other_model');
$ci->other_model->call_method();



Can a model use another model? - El Forum - 01-13-2010

[eluser]tomcode[/eluser]
I had once the same problem and if If I remember right, I got I it working by just loading (here I use Your model names) the Person model before the Formulario_model.