dongyu9894 2017-09-04 15:02
浏览 2178
已采纳

批量插入并获得返回的ids laravel

I have an array like this one :

 0 => array:2 [
    "name" => "Data1"
    "type" => "value1"
  ],
 1 => array:2 [
    "name" => "Data2"
    "type" => "value2"
  ]

i want to insert them in single query in the database and retrieve their ids without any additional query.

So far i have tried insertGetId

MyModel::insertGetId($array)

but i have noticed it inserts bulk rows but return the last id.

  • 写回答

2条回答 默认 最新

  • doumu1212 2017-09-05 01:03
    关注

    Well You Can Get The Last Id from the table .. Then After The Insertion Add The Last id To The Count of your array .. But you Will face a problem and that is if you have 2 or more users inserted some records into this table at the same time .. so you can use The Transaction

     try{
        DB::beginTransaction();
    
       // 1- get the last id of your table ($lastIdBeforeInsertion)
    
       // 2- insert your data
        Model::insert($array);
    
      // 3- Getting the last inserted ids
      $insertedIds = [];
      for($i=1; $i<=theCountOfTheArray; $i++)
         array_push($insertedIds, $lastIdBeforeInsertion+$i);
    
    });
    
        DB::commit();
    }catch(\Exception $e){
        DB::rollback();
    }
    

    or

    DB::transaction(function() {
    
       // 1- get the last id of your table ($lastIdBeforeInsertion)
    
       // 2- insert your data
       Model::insert($array);
    
      // 3- Getting the last inserted ids
      $insertedIds = [];
      for($i=1; $i<=theCountOfTheArray; $i++)
         array_push($insertedIds, $lastIdBeforeInsertion+$i);
    
    });
    

    Database Transaction Documentation

    Very Useful Article About Database Transactions

    Edit

    You Can make a unique Column and Call it for Example unique_bulk_id .. This will hold randomly generated string for the inserted data .. after the insertion you can get the inserted data by This unique_bulk_id.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn