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

Laravel 10评论POST请求错误指向评分表的问题求助

Laravel 10评论接口500错误(SQLSTATE[42S22])修复方案

问题根源

控制器的CreateComment方法错用了BookRating模型,本该使用对应评论表的CreateComment模型。这导致系统试图把评论数据插入book_ratings表,但该表不存在Comment字段,直接触发SQL字段不存在错误。

修复步骤

1. 修正控制器的模型实例化

打开BookRatingController,找到CreateComment方法,将模型实例化代码替换为对应评论的模型:

// 原错误代码
$rating = new BookRating();
$rating->Comment = $request->Comment;
$rating->userId = $request->userId;
$rating->bookId = $request->bookId;
$rating->save();

// 修正后代码
$comment = new CreateComment();
$comment->Comment = $request->Comment;
$comment->userId = $request->userId;
$comment->bookId = $request->bookId;
$comment->save();

2. (可选)优化控制器职责划分

目前评分和评论接口都挂载在BookRatingController下,从代码整洁度考虑,建议单独创建CommentController处理评论逻辑,路由同步调整:

// routes/api.php 或 web.php
Route::post('/ratings', [BookRatingController::class, 'CreateRating']);
Route::post('/comments', [CommentController::class, 'CreateComment']);

3. 检查模型填充配置

确认CreateComment模型的$fillable属性包含所有允许插入的字段,若模型名与表名命名规则不匹配,需手动指定表名:

class CreateComment extends Model
{
    protected $fillable = ['Comment', 'userId', 'bookId'];
    protected $table = 'create_comments'; // Laravel默认用蛇形命名,这里表名是create_comments,需手动指定
}

验证修复

用Postman重新发送评论POST请求,确认数据成功写入create_comments表,不再出现SQL字段不存在错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 02:42:35