简体   繁体   English

Laravel:如何获得总帖子的总评论数

[英]Laravel: How to get count of total Comments of total Posts

I have 10000 posts and each post have many comments.我有 10000 个帖子,每个帖子都有很多评论。 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.共有 9 条评论。 i want get this count.我想得到这个计数。

In laravel is possible to get count of hasMany relation of one row在 Laravel 中可以获取一行的 hasMany 关系的计数

Post::first()->comments()-count()

I need like this:我需要这样:

Post::get()->comments()-count()

i dont want use foreach because my server may get down.我不想使用 foreach,因为我的服务器可能会宕机。

You could do in at least two ways.你至少可以通过两种方式来做。

$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):直接从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');

OR或者

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM