【问题标题】:Bulk insert and get returned ids laravel批量插入并获取返回的 ID Laravel
【发布时间】:2018-02-12 20:26:49
【问题描述】:

我有一个这样的数组:

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

我想将它们插入到数据库中的单个查询中,并在不进行任何额外查询的情况下检索它们的 ID。

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

MyModel::insertGetId($array)

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

【问题讨论】:

  • 创建自定义方法。这有什么问题吗?
  • 检查 this 可能对你有帮助,没有内置代码来获取 ID,所以你必须像那个链接那样做自定义代码。
  • @PandhiBhaumik 三问用户? , 我认为当项目规模扩大时会很多
  • @wahdan 我想过,循环遍历每个插入并收集数组中的 id,最后返回该数组。这不是最佳解决方案:D

标签: php mysql laravel


【解决方案1】:

你可以从表中获取最后一个 ID .. 然后在插入之后将最后一个 id 添加到数组的计数中.. 但是你会遇到一个问题,那就是如果你有 2 个或更多用户插入了一些记录同时进入这个表..所以你可以使用 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();
}

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

编辑

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

【讨论】:

  • 说“制作一个独特的列”听起来太模棱两可,人们会认为制作一个具有独特约束的列,这显然行不通。
  • $lastIdBeforeInsertion 可能不是事实来源。当最后一条记录被删除时,它会产生一个间隙。示例:您的最后一条记录的 ID 为 23,您将其删除,您的最后一条记录的 ID 为 22,但您的下一条记录的 ID 为 24。
【解决方案2】:

正如我在@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);

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多