Welcome Guest, Not a member yet? Register   Sign In
Calling other Model functions inside the Model
#1

[eluser]lookatthosemoose[/eluser]
Hi everyone. Quick question.

Is it possible to call one of the models other functions from within another function in the same model.

example:

Code:
function Address(){
        // Call the Model constructor
        parent::Model();
    }
    
    function get_alias_id($alias){
        $this->db->get_where('addresses',array('alias' => '$alias'));
        $query = $this->db->get('addresses');
        return $query->result();
    }
    
    function add(){
         $new_alias_id = get_alias_id($_POST['alias']);
    }
}

I've tried this->address->get_alias_id() and $this->get_alias_id() as well. No Luck.
I get this error -- Message: Trying to get property of non-object


Thoughts?

Thanks

--Eric--
#2

[eluser]tonanbarbarian[/eluser]
This is a basic OO question.
You really should look into the PHP manual on how to use Objects

To do this you us the $this construct
Code:
$new_alias_id = $this->get_alias($_POST['alias']);
#3

[eluser]lookatthosemoose[/eluser]
Yes, I was under the same impression that $this->get_alias_id(...) would work as well.
Perhaps I have a typo, b/c that was the first thing I tried. I'll double check tomorrow. Time to call it a night. Thanks!

--Eric--
#4

[eluser]Chris Newton[/eluser]
[edit note: I wrote some stuff earlier that I realized didn't address the problem, which I've revised below]

Your model class needs to be created a little differently, and you have a variable in quotes when it shouldn't be.

Try something like this:
Code:
class Address extends Model
{
     function Address(){
        // Call the Model constructor
        parent::Model();
    }
    
    function get_alias_id($alias){
        $this->db->select('*');
        $this->db->from('addresses');
        $this->db->where('alias',$alias);
        $query=$this->db->get();
        if ($query->num_rows() > 0)
        {
          $row = $query->first_row();
           return $row->alias;
        }  
         else
        {
             return NULL;
        }
    }
    
    function add(){
         $new_alias_id = $this->get_alias_id($this->input->post('alias');
    }
}
#5

[eluser]lookatthosemoose[/eluser]
Edit: I just realized the function below is a different one than referenced above, but same concept.

I'm using the active record class/methodology. So Im endeavoring to keep all the methods in this fashion:

Code:
function get_alias($id,$return_value=FALSE){
       $query = $this->db->get_where('addresses',array('alias_id' => $id));

        if($return_value){
            $row = $query->first_row();
            return ($query->num_rows() > 0) ? $row->alias : NULL;
        }
        
        return $query->$query->result();
    }

I've added an optional parameter to dictate whether to return the object, or the value. Thus, best of both worlds.




Theme © iAndrew 2016 - Forum software by © MyBB