【问题标题】:Laravel - How do I get the total number of comments?Laravel - 我如何获得评论总数?
【发布时间】:2022-01-27 01:45:30
【问题描述】:

我想获取帖子中的 cmets 总数。

两种型号。 发布评论。 Comments 与 Post 具有 p多态关系。评论可以在自己上有其他的cmets。它们是 cmets 上的 cmets / 对评论的回复。这种关系由评论数据库表中的列 comment_parent 表示。

这是我的模型:

发帖

public function comments()
{
    return $this->morphMany(Comment::class, 'commentable')->whereNull('comment_parent');
}

评论

public function commentable()
{
    return $this->morphTo();
}

public function replies()
{
    return $this->hasMany(Comment::class, 'comment_parent')->orderBy('id', 'desc');
}

刀片

在我的刀片中,Count 只显示第一级 cmets 的数量。对 cme​​ts 的所有回复 不要。如何以及在哪里可以确定具有回复计数的所有 cmets 的数量?

post.blade.php

<h3>Comments ( {{ $post->comments->count() }} )</h3>

@foreach($comments as $comment)
    <div>{{ $comment->content }}</div>

    <!-- show replies -->
    <div>
        @foreach($comment->replies as $reply)
            <div class="bg-blue-100 ml-20 my-2">
        <div>{{ $reply->content }}</div>
            </div>
        @endforeach
    </div>
@endforeach

后控制器

public function show(Post $post) {
    $post->load(['comments' => function ($query) {
        $query->where('comment_approved', true)->orderBy('id','desc');
    }]);        
        
    return view('page.post', ['post' => $post]);
}

【问题讨论】:

    标签: laravel


    【解决方案1】:

    使用没有条件-&gt;whereNull('comment_parent')count() 的新关系。

    public function allComments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
    
    <h3>Comments ( {{ $post->allComments()->count() }} )</h3>
    

    如果你想在控制器中这样做

    public function show(Post $post) {
        $post->load(['comments' => function ($query) {
            $query->where('comment_approved', true)->orderBy('id','desc');
        }])->loadCount('allComments');        
            
        return view('page.post', ['post' => $post]);
    }
    

    然后在刀片中使用它作为

    <h3>Comments ( {{ $post->all_comments_count }} )</h3>
    

    【讨论】:

    • 谢谢。这就是我迄今为止一直在做的事情。我想我可以在查询中做到这一点。
    • @MaikLowrey 您可以在控制器中预加载它,检查第二部分。如果它回答了您的问题,请将其标记为“答案”以完成您的帖子。
    猜你喜欢
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    • 1970-01-01
    相关资源
    最近更新 更多