批量插入并获取返回的 ID Laravel

wah*_*dan 5 php mysql laravel

我有一个这样的数组:

 0 => array:2 [
    "name" => "Data1"
    "type" => "value1"
  ],
 1 => array:2 [
    "name" => "Data2"
    "type" => "value2"
  ]
Run Code Online (Sandbox Code Playgroud)

我想在数据库中的单个查询中插入它们并检索它们的 id 而不需要任何额外的查询。

到目前为止我已经尝试过 insertGetId

MyModel::insertGetId($array)
Run Code Online (Sandbox Code Playgroud)

但我注意到它插入了大量行但返回了最后一个 id。

Ali*_*eda 7

好吧,您可以从表中获取最后一个ID..然后在插入后将最后一个ID添加到数组的计数中..但是您将面临一个问题,那就是如果您有2个或更多用户在该表中插入了一些记录同时..这样你就可以使用交易

 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();
}
Run Code Online (Sandbox Code Playgroud)

或者

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);

});
Run Code Online (Sandbox Code Playgroud)

数据库事务文档

关于数据库事务的非常有用的文章

编辑

您可以创建一个唯一的列并调用它作为示例unique_bulk_id..这将为插入的数据保存随机生成的字符串..插入后您可以通过 This 获取插入的数据unique_bulk_id