Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

Depending on how you have set up the relationships on your models, you can take advantage of Eloquent's Eager Loading and make use of the constraint features that are available.

The following are just example models, you will have to adjust them to match your column names and your relationships:

This is an example Post model:

class Post extends Eloquent {

    protected $table = 'posts';

    /**
     * Returns a collection of comments.
     */
    public function comments()
    {
        return $this->hasMany('Comment', 'post_id');
    }

}

This is what a Comment model might look like:

class Comment extends Eloquent {

    protected $table = 'comments';

    /**
     * Returns a comment's author.
     * @return User
     */
    public function author()
    {
        return $this->belongsTo('User', 'user_id');
    }

    /**
     * Returns a comment's associated post.
     */
    public function post()
    {
        return $this->belongsTo('Post', 'post_id');
    }

}

After setting up these relationships, you can accomplish what you want like this:

$posts = Post::where('category_id', '=', 5)->with(array('comments' => function($query)
        {
            $query->with(array('author'));
        }))->get();

Then, when you are looping through the result, you can access the comments and authors like this:

foreach ($posts as $post)
{
    foreach ($post->comments as $comment)
    {
        // Here you would output the comment's message or show the authors name.
        // Again, this is an example:
        echo $comment->message;
        echo '<br> Posted by: '.$comment->author->email;
    }
}

Hope this helps! But I highly recommend reading the docs for Eloquent's Eager Loading and Eloquent Relationships for even more information.

Last updated 2 years ago.
0

Thank you Johnathon for this long answer.

Last updated 2 years ago.
0

You could just do this:

Post::with('comments.author')->where('category_id', 5)->get();

The dot syntax allows for nested relationships to be eager loaded.

Last updated 2 years ago.
0

shabushabu said:

You could just do this:

Post::with('comments.author')->where('category_id', 5)->get();

The dot syntax allows for nested relationships to be eager loaded.

Good to know! Thanks!

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

mehmet mehmet Joined 18 May 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.