3
votes

I'm going through my laravel application and trying to fix any n+ issues I can find. I have come across one scenario which isn't really an n+ but not sure what to call it.

I have 2 models Post, Comment. A post has many comments and a comment belongs to a post

When I loop through all my posts I would like to display a count of how many comments they contain. I've been able to do this fine. But the problem it is 2 queries.

How do I update the following Eloquent query to add a column for comments count.

Post::where('status', 1)->get();

Thanks

2

2 Answers

8
votes

Update

As of Laravel 5.2.32, a new method was added to the query builder to help with this. When you add the withCount($relation) method to your query, it will add a {relation}_count field to the results, which contains the count of the supplied relation.

So, your query would be:

$posts = Post::where('status', 1)->withCount('comments')->get();

foreach($posts as $post) {
    echo $post->comments_count;
}

You can read more in the documentation here.


Original

@JarekTkaczyk has a good blog post that does what you're looking for. Check out the article here.

Basically, you'll be creating a relationship that contains the count of comments for the post, and you'll eager load the relationship (thus avoiding the n+1). He also has some syntactic sugar in there for accessing the count through an attribute accessor.

0
votes

Either just use count on the relationship, or if you think it's necessary, you could add a 'num_comments' to the Post model and increment it on the creation of a comment:

$post->comments()->count();

or in the comments model:

public function create( $commentData ){

    $result = $this->fill( $commentData );
    $this->post()->increment('num_comments');

    return $result;
}