我有10000个帖子,每个帖子都有很多评论。上帖子时,我需要计算所有评论数。
[
'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',
],
],
]
共有9条评论。我想得到这个计数。
在laravel中可以获取具有一行的hasMany关系的计数
Post::first()->comments()-count()
我需要这样:
Post::get()->comments()-count()
我不想使用foreach,因为我的服务器可能会停机。
答案 0 :(得分:2)
您可以至少采用两种方式。
$posts = Post::withCount('comments')->get();
$total = $posts->sum('comments_count');
Comment
模型进行计数:$total = Comment::all()->count();
答案 1 :(得分:1)
也许您必须采用其他方式:
Comment::whereNotNull('post_id')->count();
答案 2 :(得分:1)
Post::withcount('comment')->where('post_id', $post_id)->get();
尝试这个。
答案 3 :(得分:1)
$posts = Post::withCount('comments')->get();
$total = $posts->sum('comments_count');
OR
$total = Comment::all()->count();