Laravel 5.7不同帖子的评论数

时间:2019-02-20 08:47:51

标签: php laravel

我被困在获得帖子评论数的位置,但是它显示了每个帖子上所有帖子的所有评论数。我想知道如何在帖子ID的刀片注释计数中输出

这是控制器:

  $posts = $posts->orderBy("posted_at", "desc")
        ->paginate(config("blogetc.per_page", 10));

    $comments = BlogEtcComment::all();


    return view("blogetc::index", [
        'posts' => $posts,
        'title' => $title,
        'comments' => $comments,
    ]);

刀片:

@foreach($posts as $post)
<section class="blog_area p_120">
        <div class="container">
            <div class="row">
                <div class="col-lg-8">
                    <div class="blog_left_sidebar">
                        <article class="blog_style1">
                            <div class="blog_img">
                                <img class="img-fluid" src="blog_images/{{$post->image_large}}" alt="">
                            </div>
                            <div class="blog_text">
                                <div class="blog_text_inner">
                                    <div class="cat">
                                        <a class="cat_btn" href="{{$post->url()}}">{{$post->slug}}</a>
                                        <a href="#"><i class="fa fa-calendar" aria-hidden="true"></i>{{$post->created_at}}</a>
                                        <a href="{{$post->url()}}"><i class="fa fa-comments-o" aria-hidden="true"></i> {{count($comments)}}</a>
                                    </div>
                                    <a href="{{$post->url()}}"><h4>{{$post->title}}</h4></a>
                                    <p>{!! $post->generate_introduction(400) !!}</p>
                                    <a class="blog_btn" href="{{$post->url()}}">Lasīt vairāk</a>
                                </div>
                            </div>
                        </article>
                    </div>
                </div>
            </div>
        </div>
</section>
@endforeach

2 个答案:

答案 0 :(得分:0)

您可以使用withCount()获取特定帖子的评论数:

$posts = $posts->withCount('comments')
        ->orderBy("posted_at", "desc")
        ->paginate(config("blogetc.per_page", 10));

以上要求您在comments模型上具有Post关系:

Post型号:

public function comments()
{
    return $this->hasMany(BlogEtcComment::class);
}

BlogEtcComment型号:

public function post()
{
    return $this->belongsTo(Post::class);
}

然后在Blade中:

@foreach($posts as $post)
  <p>Post : $post->id</p>
  <p>Comments : $post->comments_count</p>
@endforeach

答案 1 :(得分:0)

// Quickfix:

///假设您的posts表被称为posts,而在blogetccomments表中// //您有一个post_id列指向原始帖子。尝试类似

$posts = DB::table('posts')
    ->leftJoin('blogetccomments', 'posts.id', '=', 'blogetccomments.post_id')
    ->selectRaw('posts.*, count(blogetccomments.post_id) as commentcount')
    ->groupBy('posts.id')
    ->get();

在刀片模板中,访问每个帖子的评论计数,如下所示。

@foreach($posts as $post)
...
{{$post->title}}...
{{$post->commentcount}}

...
@endforeach