Laravel中使用Select2批量更新选中模型ID报错求助
问题:批量更新选中模型时出现字符串偏移错误
问题场景
我有一个从数据库获取模型ID的Select2多选下拉框,选中的ID为:
["3219","3220"]
希望用表单中的输入值批量更新每个选中ID对应的模型。
表单代码
<div class="form-group"> <input hidden type="text" value="{{$invoices->id}}" name="invoice_id" id=""> <label for="">Colete neasociate</label> <select name="id[]" multiple="multiple" class="form-control js-example-basic-single" id=""> <option value=""></option> @foreach ($coletes as $coletes) <option value="{{$coletes->id}}"> Coletul {{$coletes->ID}} cu nr {{$coletes->numarcursa}} </option> @endforeach </select>
控制器代码
$colete = $request->input('id'); foreach($colete as $row){ $colete = colete::find($row['id']); $colete->invoice_id = $request->invoice_id; $colete->save(); }
错误信息
Cannot access offset of type string on string
解决建议
- 错误原因:
$request->input('id')返回的是字符串数组(如["3219","3220"]),循环中的$row是单个ID字符串,并非数组,因此不能用$row['id']取值。 - 修复后的基础版控制器代码:
$coleteIds = $request->input('id'); $invoiceId = $request->invoice_id; foreach($coleteIds as $id){ // 先判断模型是否存在,避免无匹配ID时报错 $colete = Colete::find($id); if($colete){ $colete->invoice_id = $invoiceId; $colete->save(); } }
- 性能优化方案:使用批量更新替代循环逐个保存,仅需一条SQL语句,效率更高且自动兼容无匹配ID的情况:
Colete::whereIn('id', $request->input('id')) ->update(['invoice_id' => $request->invoice_id]);
内容的提问来源于stack exchange,提问作者Catalin-Gabriel
相关产品推荐
相关产品推荐

