批量插入并返回IDs Laravel [英] Bulk insert and get returned ids laravel
问题描述
我有一个像这样的数组:
I have an array like this one :
0 => array:2 [
"name" => "Data1"
"type" => "value1"
],
1 => array:2 [
"name" => "Data2"
"type" => "value2"
]
我想在数据库中的单个查询中插入它们,并在不进行任何其他查询的情况下检索它们的ID.
i want to insert them in single query in the database and retrieve their ids without any additional query.
到目前为止,我已经尝试过insertGetId
So far i have tried insertGetId
MyModel::insertGetId($array)
但是我注意到它会插入批量行,但返回最后一个ID.
but i have noticed it inserts bulk rows but return the last id.
推荐答案
好了,您可以从表中获取最后一个ID.然后在插入之后将最后一个ID添加到数组的计数中.问题,即如果您有2个或更多用户同时在此表中插入了一些记录..因此,您可以使用The Transaction
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();
}
或
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
..这将保存插入数据的随机生成的字符串..插入后,您可以通过This unique_bulk_id
获取插入的数据.
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
.
这篇关于批量插入并返回IDs Laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!