Welcome Guest, Not a member yet? Register   Sign In
ActiveRecord for CodeIgniter: Rails-style model interactions
#66

[eluser]frith[/eluser]
OK the issue was my own... I was expecting activerecord to magically declare the models for me which was dumb. If all three are declared in the controller you can quite easily create N-tier relationships like this.


Code:
$this->load->model('genre');
$this->load->model('book');
$this->load->model('author');

$genres = $this->genre->counting_books()->find_all();

echo "<ul>";
foreach($genres as $genre)
{
    echo '<li>'.$genre->name.' ('.$genre->num_books.')</li>';
    echo '<ul>';
    $books = $genre->fetch_related_books();
    foreach ($books as $book)
    {
        $authors = $book->fetch_related_authors();
        $authors_str = "";
        foreach ($authors as $author)
        {
            $authors_str .= ", ".$author->name;
        }
        echo '<li>'.$book->name.' by '.ltrim($authors_str,', ').'</li>';
    }
    echo '</ul>';
}
echo '</ul>';

@Andre83
It was you're post that made me realize what I was doing wrong. After looking at the code I realized that the _fetch_related method quite cleverly detects if you've instantiated the models and if you have gives you full models and if you haven't gives you a standard class (awesome!) The only difference is that you changed it to store the instance inline inside $this rather than returning it seperately. I can't think of any performance issues with doing it that way so it comes down to personal preference... I think i like your tweak so the above code becomes:


Code:
$this->load->model('genre');
$this->load->model('book');
$this->load->model('author');

$genres = $this->genre->counting_books()->find_all();

echo "<ul>";
foreach($genres as $genre)
{
    echo '<li>'.$genre->name.' ('.$genre->num_books.')</li>';
    echo '<ul>';
    $genre->fetch_related_books();
    foreach ($genre->books as $book)
    {
        $book->fetch_related_authors();
        $authors_str = "";
        foreach ($book->authors as $author)
        {
            $authors_str .= ", ".$author->name;
        }
        echo '<li>'.$book->name.' by '.ltrim($authors_str,', ').'</li>';
    }
    echo '</ul>';
}
echo '</ul>';

The advantage i can see is that it makes the object easier to serialize and stick in a session or pass around to other functions as apposed to seperate objects. Chromice, I'd encourage you to incorporate Andre83's suggested tweak going forward.

Thanks guys... again, loving this.


Messages In This Thread
ActiveRecord for CodeIgniter: Rails-style model interactions - by El Forum - 11-15-2007, 02:58 PM



Theme © iAndrew 2016 - Forum software by © MyBB