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

如何展示特定帖子/服务的评论?解决SQL列不存在报错问题

解决评论展示时的SQL字段不存在错误

看起来你在服务详情页展示评论时踩了个典型的数据库关联坑——错误提示已经很明确了:你的comments表根本没有service_id这个字段,但代码却试图用它来筛选服务相关的评论。咱们一步步来解决:

1. 先确认数据库表结构

首先得搞清楚你的comments表到底有没有service_id字段。你可以用MySQL命令行或者phpMyAdmin执行这条命令查看表结构:

DESCRIBE comments;

如果结果里确实没有service_id,那这就是问题根源——因为你要关联服务和评论,必须在评论表中存储服务的ID。

给comments表添加service_id字段(Laravel项目)

如果是Laravel项目,用迁移来添加字段最稳妥:

  • 先创建迁移文件:
php artisan make:migration add_service_id_to_comments_table
  • 打开生成的迁移文件,写入字段定义:
public function up()
{
    Schema::table('comments', function (Blueprint $table) {
        // 允许为空,因为你的评论可能同时关联帖子和服务
        $table->unsignedBigInteger('service_id')->nullable();
        // 建立外键关联services表的id字段,服务删除时自动删除关联评论
        $table->foreign('service_id')->references('id')->on('services')->onDelete('cascade');
    });
}

public function down()
{
    Schema::table('comments', function (Blueprint $table) {
        $table->dropForeign(['service_id']);
        $table->dropColumn('service_id');
    });
}
  • 运行迁移生效:
php artisan migrate

2. 检查评论存储的逻辑

你说评论存储功能正常,但要确认存储服务评论时,是不是把service_id正确写入了数据库。比如在CommentsController的store方法里,要确保传入并保存了服务ID:

public function store(Request $request)
{
    $validated = $request->validate([
        'content' => 'required|string',
        // 其他验证规则根据你的需求加
    ]);

    Comment::create([
        'content' => $validated['content'],
        'user_id' => auth()->id(),
        'service_id' => $request->service_id, // 这里必须传入当前服务的ID
        // 如果是帖子评论,这里就换成'post_id' => $request->post_id
    ]);

    return back();
}

3. 修正模型关联和视图查询逻辑

接下来要确保模型之间的关联是正确的,这样在视图里才能正常调用评论:

Service模型(app/Models/Service.php)

public function comments()
{
    // 默认会关联comments表的service_id字段,和我们刚加的字段对应
    return $this->hasMany(Comment::class);
}

Comment模型(app/Models/Comment.php)

public function service()
{
    return $this->belongsTo(Service::class);
}

然后在控制器的服务详情方法里,把关联的评论传递给视图:

public function show($id)
{
    $service = Service::with('comments')->findOrFail($id);
    return view('service.showservice', compact('service'));
}

最后在showservice.blade.php里遍历评论:

@foreach($service->comments as $comment)
    <div class="comment">
        <p>{{ $comment->content }}</p>
        <small>By {{ $comment->user->name }}</small>
    </div>
@endforeach

4. 区分帖子和服务的评论逻辑

因为你同时需要展示帖子和服务的评论,建议你的comments表同时有post_id和service_id两个可空字段,分别关联帖子和服务。存储时根据当前场景(是帖子评论还是服务评论)存入对应的ID,查询时也通过对应的字段筛选,就不会搞混了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:44:31