Welcome Guest, Not a member yet? Register   Sign In
Active Record - Use a main method to rectrieve all, second method to retrieve 1 or filter ?
#1

[eluser]glasses092[/eluser]
Hi everyone,

Can anyone help me with this, I've been trying to do some code in my model that has one main method to retrieve all results (lots of selects/joins are going to be in here) and a second method that calls this method to filter based on the where...

Code:
<?
    public function get_all()
    {
        $this->db->get($this->table);
        //lots of joins in here
        return $this->db->last_query(); //Do I have to have to return the SQL, can I return the object?
    }
    
    public function get_one($id)
    {
        $query = $this->get_all();
        $result = $this->db->where('id', $id)->query($query);
        return $result;
    }
?>

The where clause is not applied, but I've no idea why...

I need to use a main method (get_all) as I don't want to rewrite all joins, selects etc... again and I don't want to put a 'where' clause in the 'get_all' method...

Does anyone have any ideas/suggestions/ways to make it work, I'd appreciate the help.

Thanks
#2

[eluser]Buso[/eluser]
try this

Code:
public function get_all()
    {
        // joins here
        $query = $this->db->get($this->table);

        return $query->result(); // try returning the array of objects. You could add a $query->num_rows() check before
    }
    
    public function get_one($id)
    {
        $this->db->where('id', $id);
        $this->db->limit(1); // just in case
        $result = $this->get_all();
        return $result; // you could return the object already taken from the array: $result->row()
    }
#3

[eluser]glasses092[/eluser]
Thanks Buso, Ill give it a shot, Cheers Smile
#4

[eluser]glasses092[/eluser]
Hi Buso,

Tried that and it works perfectly...

Im a bit unsure of why it works tho, I thought after you got the result or result_array, that was it - no further wheres/limits were allowed... obviously not...

Can you explain a little why it works...

This works as well...

Code:
public function get_all()
{
    return $this->db->get($this->table);
}

public function get_one()
{
    $this->db->where('id', 342);
    $result = $this->get_all()->result_array();
    return $result;
}
#5

[eluser]WanWizard[/eluser]
In this example there are no further wheres/limits.

In PHP5 you can use chaining, and as $this->get_all() returns an object, this
Code:
$result = $this->get_all();
$result = $result->result_array();

is the same as

Code:
$result = $this->get_all()->result_array();




Theme © iAndrew 2016 - Forum software by © MyBB