doulei2100 2019-04-14 12:56
浏览 99

数据库Laravel中的多选引导插入

I'm trying to create multi selection bootstrap output to save in database but I'm getting an array in my controller like ["6","7"]. How I can save this?

There is 2 selection that means 2 row must created.

The query I was trying:

$table = Pool_user::updateOrInsert(['pool_id' => [$string1], 'user_id' => $request['id']]);

Can anyone help me to solve this?

  • 写回答

1条回答 默认 最新

  • dongtu4028 2019-04-14 15:26
    关注

    By responding directly to your question, you need to create an array of arrays with the values you want to enter.

    Something like this:

    $array = [];
    foreach($request['pool_ids'] as $pool_id){ //$request['pool_ids'] -> ["6","7"]
       array_push($array, [
          'pool_id' => $pool_id,
          'user_id' => $request['id']
       ]);
    }
    
    $table = Pool_user::insert($array);
    

    However, considering that Pool_user is a Pivot table of a Many to Many relationship, there is a much better method of doing this. Let's say in User Model, have a relationship called polls().

    You can simply ask the Eloquent to synchronize the relationships:

    $user = User::find($request['id']);
    $user->polls()->sync($request['pool_ids']); //$request['pool_ids'] -> ["6","7"]
    

    Hope this helps

    评论

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器