繁体   English   中英

如何检索帖子列表页面中所有帖子的评论

[英]How can I retrieve comments of all posts in posts list page

我的问题是:我想显示每个帖子的用户评论数。 我有一个帖子管理员,我无法获得每个帖子的ID。

public function myposts(Post $post,Pcomment $pcomment){
    if(Auth::check()){
        $agent = new Agent();
        $posts = Post::where('user_id', auth()->user()->id)->orderBy('id', '-ASC')->paginate(5);
        $pcomments = $pcomment->where('post_id',"=", $post->id)->get();
        return view('posts.myposts',compact('posts','agent','pcomments'));
    }else{
        return redirect('/login');
    }
}

如果你正确地设置了模型之间的关系

class Post extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function comments()
    {
        return $this->hasMany('App\Comment');
    }
}

然后你可以运行以下命令获取帖子上的所有用户评论

$user_comments = $post->comments()->where('user_id', auth()->user()->id)->get();

如果您只想要计数,请执行以下操作

$user_comment_count = $post->comments()->where('user_id', auth()->user()->id)->count();

尝试以下代码,希望这对您有所帮助

Post.php(型号)

public function comments() {
    return $this->hasMany('App\Comment');
}

调节器

->withCount('comments')函数用于计算每个帖子的评论。

$posts = Post::with('comments')->withCount('comments')->where('user_id', auth()->user()->id)->orderBy('id', '-ASC')->paginate(5);

暂无
暂无

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

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