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.
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.
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!
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community