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

7

我有一个像这样的数组:

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

我希望您能在不进行额外查询的情况下,将它们以单个查询插入到数据库中并检索其ID。目前我尝试了insertGetId
MyModel::insertGetId($array)

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


1
创建自定义方法。这有什么问题吗? - Sagar Gautam
1
请查看此链接(https://dev59.com/YJTfa4cB1Zd3GeqPOkgl#35524376),它可能会对您有所帮助。没有内置代码可以获取ID,因此您必须像该链接中那样编写自定义代码。 - Bhaumik Pandhi
您可以查看此问题 https://dev59.com/MV8f5IYBdhLWcg3wFfP_ - Sagar Gautam
@PandhiBhaumik 三个询问的用户? 我认为在项目规模时这太多了。 - wahdan
1
@wahdan 我考虑过循环遍历每个插入并收集ID到数组中,最后返回该数组。但这不是最优解 :D - Sagar Gautam
我认为一个解决方案可能是,通过返回的最后一个id,我们可以得到插入的总记录数。如果你正在使用SQL,那么将id递增到插入的记录数,然后你将在一个递增循环中得到结果。 - Sagar Gautam
2个回答

7

你可以从表中获取最后一个id,然后在插入后将该id添加到你的数组计数中。但是如果在同一时间有两个或更多用户向该表中插入记录,则会遇到问题。因此,你可以使用事务。

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

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

});

数据库事务文档

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

编辑

你可以创建一个唯一列,例如称之为 unique_bulk_id .. 这将保存插入数据的随机生成字符串 .. 插入后,你可以通过此 unique_bulk_id获取插入的数据。


说“创建一个独特的列”听起来太模糊了,人们会认为是创建一个带有唯一约束的列,这显然不可行。 - Chris
1
$lastIdBeforeInsertion 不一定是真实的标识。当最后一条记录被删除时,会产生间隙。例如:您的最后一条记录的ID为23,您将其删除,您的最后一个id将是22,但是您的下一条记录将具有ID 24。 - Clément Baconnier

3

如我在@ali-beshir的回答中所述;

$lastIdBeforeInsertion 可能不是真正的数据来源。当最后一条记录被删除时,会产生空缺。例如:您的最后一条记录的ID为23,您将其删除,您的最后一个ID将为22,但是下一条记录将具有ID 24。

因此,我只获取了最后一个ID,我认为这更可靠。

DB::transaction(function() {

    Model::insert($data);
   
    $lastId = Model::orderByDesc('id')->first()->id;

    $ids = range($lastId - count($data) + 1, $lastId);

});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接