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

Laravel关联问题:插入Food表ID至Ratings表时出现数据格式错误

解决Laravel中插入Rating时food_id传入空数组的问题

嘿,这个错误我太熟悉了,咱们一步步拆解解决它!

先看你抛出的错误信息,关键点很明显:

Invalid datetime format: 1366 Incorrect integer value: '[]' for column `efoodies`.`ratings`.`food_id` at row 1 (SQL: insert into `ratings` (`comment`, `food_id`, `user_id`, `updated_at`, `created_at`) values (dsa, [], 2, 2020-10-30 09:07:37, 2020-10-30 09:07:37))

数据库明确告诉你,food_id字段需要整数类型,但你传了个空数组[],这肯定不符合要求。

问题出在哪?

来看你的addComment方法里的这段代码:

public function addComment(Request $request, $slug = null) { 
    $products = Food::where("id", $slug)->get(); 
    $ratings = new Rating(); 
    $ratings->comment = $request->input('comment'); 
    $ratings->food_id = $products; // 这里就是核心问题!
    Auth::user()->ratings()->save($ratings); 
}
  • Food::where("id", $slug)->get()返回的是Laravel集合(Collection),哪怕只匹配到一条数据,它也是数组形式的集合。直接把整个集合赋值给food_id,就会导致插入时传入数组(没数据就是空数组[]),完全不是我们需要的单个整数ID。

修正方案

我们需要获取单个Food模型实例,再取出它的ID,这里有两种简洁的实现方式:

方式1:用first()获取单个模型+空值判断

public function addComment(Request $request, $slug = null) { 
    // 用first()获取单个Food模型,而非get()返回集合
    $product = Food::where("id", $slug)->first(); 
    
    // 先判断是否找到对应商品,避免后续代码报错
    if(!$product) {
        abort(404);
    }
    
    $ratings = new Rating(); 
    $ratings->comment = $request->input('comment'); 
    $ratings->food_id = $product->id; // 取出单个模型的ID赋值
    Auth::user()->ratings()->save($ratings); 
    
    // 可以添加跳转或成功提示,提升用户体验
    return back()->with('success', '评论提交成功!');
}

方式2:更优雅的findOrFail()自动处理404

public function addComment(Request $request, $slug = null) { 
    // findOrFail会自动根据ID查找模型,找不到直接返回404异常,省去手动判断
    $product = Food::findOrFail($slug); 
    
    $ratings = new Rating(); 
    $ratings->comment = $request->input('comment'); 
    $ratings->food_id = $product->id; 
    Auth::user()->ratings()->save($ratings); 
    
    return back()->with('success', '评论提交成功!');
}

额外优化建议

  1. 修正参数命名:你的路由参数叫$slug,但实际接收的是Food的ID,这很容易混淆,建议把参数名改成$id,同时路由也对应调整:

    // 路由示例
    Route::post('/product/{id}/comment', [YourController::class, 'addComment']);
    

    方法参数同步修改:

    public function addComment(Request $request, $id = null) { 
        $product = Food::findOrFail($id); 
        // 后续代码不变
    }
    
  2. 添加表单验证:防止用户提交空评论,让逻辑更严谨:

    $request->validate([
        'comment' => 'required|string|max:255',
    ]);
    
  3. 确认关联关系:确保你的模型关联已经正确定义:

    // User.php
    public function ratings() {
        return $this->hasMany(Rating::class);
    }
    
    // Rating.php
    public function food() {
        return $this->belongsTo(Food::class);
    }
    

这样修改后,就能正确把Food的ID插入到Ratings表的food_id字段,不会再出现空数组的错误啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 18:53:13