Question

I have a problem, I have 2 tables (posts, comments) and I want to select all posts + the number of their comments. I could create a column "comments" in posts and write the counter in there, but I think that's a bad solution, so I am looking for something like virtual fields/columns in mysql to get the number of comments in the posts query. Can I do this in Laravel?

No correct solution

OTHER TIPS

In your Comment Model:

public function post(){
    return $this->belongsTo('Post', 'post_id');
}

In your Post Model:

public function comments(){
    return $this->hasMany('Comment', 'post_id');
}

In your controller, get a post with all its comments.

$post = Post::with('comments')->find(1);

In your view, display the post and the number of comments it has. Assuming your post has a title field.

Post Title: {{ $post->title }}
The post has {{ $post->comments->count() }} comments
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top