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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 15:34:43