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

如何在Laravel Blade中通过ID关联评论与对应文章?

解决Laravel Blade中“post_id变量不存在”的错误

嘿,我来帮你搞定这个问题!你遇到的错误根源主要有两个:模型关联命名不符合Eloquent约定,以及多余且错误的@if判断。咱们一步步来修复:

1. 修正Post模型的关联方法

首先,一个文章对应多个评论,所以Post模型里的关联方法应该用复数形式comments()(而不是单数comment()),这样Eloquent才能正确识别一对多关联:

// app/Models/Post.php
public function comments()
{
    return $this->hasMany(Comment::class);
}

2. 更新控制器的关联预加载

既然关联方法改成了comments(),那控制器里的with()方法也要对应修改,确保预加载正确的关联数据:

// app/Http/Controllers/PostController.php
public function index(){
    // 把with('comment')改成with('comments')
    $posts = Post::with('comments', 'user')->orderBy('id', 'desc')->limit(20)->get();
    return view('post.posts')->with('posts', $posts);
}

3. 修复Blade模板的错误判断

你原来的@if($post->comment->post_id == $post->id)是完全没必要的——因为Eloquent的关联已经自动帮你筛选出了属于当前文章的评论,而且这个判断本身会报错:

  • 如果关联是单数comment(),$post->comment要么是单个Comment模型(此时post_id存在,但如果文章没有评论会返回null,访问属性直接报错);
  • 如果关联是复数但你用了单数命名,$post->comment会是一个集合,而集合没有post_id属性,这就是你看到“post_id变量不存在”错误的原因。

把模板里的评论部分改成这样:

{{-- 替换原来的@if和@foreach代码 --}}
@if($post->comments->isNotEmpty())
    @foreach($post->comments as $comment)
    <div class="row">
        <div class="col-md-12 mb-r">
            <div class="card example-1 scrollbar-ripe-malinka">
                <div class="card-body">
                    <h4 id="section1"><strong>By: {{ $comment->user->firstName }} {{ $comment->user->lastName }}</strong></h4>
                    <p>{{ $comment->comment }}</p>
                </div>
            </div>
        </div>
    </div>
    @endforeach
@endif

这样修改后,不仅能解决错误,还能在文章没有评论时不显示评论区域,体验更好。

内容的提问来源于stack exchange,提问作者I Love Code

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:25:04