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
相关产品推荐
相关产品推荐

