I have 10000 posts and each post have many comments. I need to calculate all comments count when i take posts.
[ 'post_1' => [ 'comments' => [ 'comment_1' => 'trst comment', 'comment_2' => 'trst comment', 'comment_3' => 'trst comment', ], ], 'post_2' => [ 'comments' => [ 'comment_1' => 'trst comment', 'comment_2' => 'trst comment', 'comment_3' => 'trst comment', ], ], 'post_3' => [ 'comments' => [ 'comment_1' => 'trst comment', 'comment_2' => 'trst comment', 'comment_3' => 'trst comment', ], ], ]
there are total 9 comments. i want get this count.
In laravel is possible to get count of hasMany relation of one row
Post::first()->comments()-count()
I need like this:
Post::get()->comments()-count()
i dont want use foreach because my server may get down.
Advertisement
Answer
You could do in at least two ways.
- Taking advantage of the posts that you might have already loaded counting related models:
$posts = Post::withCount('comments')->get(); $total = $posts->sum('comments_count');
- Counting directly from the
Comment
model (in your case, I’ll go for this approach):
$total = Comment::count();