Laravel:如何计算总帖子的总评论数

Laravel: How to get count of total Comments of total Posts

我有 10000 个 post,每个 post 都有很多评论。我需要计算 post 秒时的所有评论数。

[
    '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,因为我的服务器可能会宕机。

您至少可以通过两种方式进行。

$posts = Post::withCount('comments')->get();
$total = $posts->sum('comments_count');
  • 直接从 Comment 模型计算(在你的情况下,我将采用这种方法):
$total = Comment::count();

也许你必须走不同的路:

Comment::whereNotNull('post_id')->count();
Post::withcount('comment')->where('post_id', $post_id)->get();

试试这个。

$posts = Post::withCount('comments')->get();
$total = $posts->sum('comments_count');

$total = Comment::all()->count();