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

Laravel商品CRUD更新时SQL整数值错误求助(category_id传字符串)

问题分析与解决

错误根源

报错信息显示更新操作试图将category_id设为字符串'Trousers',但数据库中category_id是整数类型的外键,类型不匹配导致SQL执行失败。

问题出在更新表单的分类选择器:默认选中的<option>标签未设置value属性,当用户不修改分类直接提交时,表单会将分类名称(如'Trousers')而非分类ID传给后端。

修复方案

修改表单中分类选择的HTML代码,给默认选中的选项添加对应分类ID作为value:

<div class="form-group">
  <label>Product category</label>
  <select class="form-control select2" name="category_id" style="width: 100%;">
    <!-- 为默认选中项添加value属性,传入分类ID -->
    <option selected="selected" value="{{$product->category_id}}">{{$product->category->nom_categorie}}</option>
    @foreach ($categories as $category)
        <option value="{{$category->id}}">{{$category->nom_categorie}}</option>
    @endforeach
  </select>
</div>

额外优化建议

在后端验证规则中补充category_id的类型与存在性校验,避免无效值提交:

$request->validate([
    "prod_name" => "required",
    "prod_price" => "required|integer",
    "prod_qty" => "required|integer",
    "category_id" => "required|integer|exists:categories,id", // 新增类型与存在性校验
    "prod_image" => "image|nullable|max:1999"
]);

内容的提问来源于stack exchange,提问作者C.J

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 17:15:53