You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取帖子列表页所有帖子评论?及个人帖子评论数展示问题求助

解答你的两个Laravel帖子评论相关问题

嘿,让我来帮你搞定这两个问题,先从你贴了代码的第二个问题入手,因为这个更具体~

问题2:展示每篇帖子的评论数量,解决无法获取单个帖子ID的问题

你当前代码的问题在于:你在方法里注入了Post $post,但这个方法是用来展示当前用户的所有帖子列表,不是单个帖子的详情页。如果你的路由没有设置{post}参数的话,这个$post实例根本没有绑定具体的帖子,所以$post->id自然拿不到有效值啦。

咱们用Eloquent关联来优雅解决这个问题,步骤如下:

  1. 在Post模型里定义和评论的关联
    打开你的Post模型,添加一个关联方法,告诉Laravel每个帖子对应多条评论:

    // app/Models/Post.php
    public function pcomments()
    {
        // 第二个参数是评论表中关联帖子的外键,默认是post_id,如果你的表字段也是这个可以省略
        return $this->hasMany(Pcomment::class, 'post_id');
    }
    
  2. 修改控制器方法,预加载评论数量
    不需要再注入Post和Pcomment实例了,用withCount方法可以直接让每个帖子对象带上评论数量的属性,高效又方便:

    public function myposts()
    {
        if(Auth::check()){
            $agent = new Agent();
            // 使用withCount预加载评论数量,会自动生成pcomments_count字段
            $posts = Post::where('user_id', auth()->user()->id)
                         ->orderBy('id', 'desc')
                         ->withCount('pcomments')
                         ->paginate(5);
            
            return view('posts.myposts', compact('posts', 'agent'));
        } else {
            return redirect('/login');
        }
    }
    
  3. 在视图中直接使用评论数量
    现在在posts.myposts视图里,你可以直接访问每个帖子的pcomments_count属性:

    @foreach($posts as $post)
        <div class="post-item">
            <h4>{{ $post->title }}</h4>
            <p>评论数:{{ $post->pcomments_count }}</p>
        </div>
    @endforeach
    

问题1:获取帖子列表页中所有帖子的评论

有两种常用的实现方式,你可以根据需求选:

  • 方式一:通过帖子关联获取(推荐,保持数据关联性)
    在获取帖子的时候用with('pcomments')预加载所有评论,这样每个帖子都会带着自己的评论集合。如果需要把所有评论合并成一个集合,可以用flatMap:

    // 控制器中获取带评论的帖子列表
     $posts = Post::where('user_id', auth()->user()->id)
                  ->orderBy('id', 'desc')
                  ->with('pcomments')
                  ->paginate(5);
     
     // 把所有帖子的评论合并成一个单独的集合
     $allComments = $posts->flatMap(function($post) {
         return $post->pcomments;
     });
    

    视图里也可以直接遍历每个帖子的评论:

    @foreach($posts as $post)
        <div class="post-item">
            <h4>{{ $post->title }}</h4>
            <div class="comments">
                <h5>评论:</h5>
                @foreach($post->pcomments as $comment)
                    <p>{{ $comment->content }}</p>
                @endforeach
            </div>
        </div>
    @endforeach
    
  • 方式二:直接通过评论模型查询
    先拿到当前用户所有帖子的ID,再通过这些ID查询对应的评论:

    $userPostIds = Post::where('user_id', auth()->user()->id)->pluck('id');
    $allComments = Pcomment::whereIn('post_id', $userPostIds)->get();
    

内容的提问来源于stack exchange,提问作者Mohamed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:13:15