[英]How to get last inserted id using Eloquent::insert()
I am inserting bulk insertions in laravel 5 like this: 我像这样在laravel 5中插入批量插入:
$data = array(
array('name'=>'Jack', 'age'=>'24'),
array('name'=>'Tom', 'age'=>'37'),
//...
);
Users::insert($data);
Any idea how to get last inserted id? 任何想法如何获取最后插入的ID?
So, you can't use insertGetId()
when bulk inserting data. 因此,批量插入数据时不能使用
insertGetId()
。 So if you want to keep DB integrity, you could do something like this: 因此,如果要保持数据库完整性,可以执行以下操作:
$lastRow = array_pop($data); // Cutting off last item from an array
Users::insert($data);
$lastId = Users::insertGetId($lastRow);
I know this is pretty dumb solution and it will create 2 queries instead of one, but if you'll not find anything better, you could use it. 我知道这是一个非常愚蠢的解决方案,它将创建2个查询,而不是一个查询,但是如果您找不到更好的查询,则可以使用它。
Alternative 另类
You could also try this: 您也可以尝试以下方法:
$lastId = DB::select('select last_insert_id()');
This could work and it shouldn't brake DB integrity : 这可能有效,并且不应该破坏数据库的完整性 :
For LAST_INSERT_ID(), the most recently generated ID is maintained in the server on a per-connection basis.
对于LAST_INSERT_ID(),将基于每个连接在服务器中维护最近生成的ID。 It is not changed by another client.
其他客户端不会更改它。 It is not even changed if you update another AUTO_INCREMENT column with a nonmagic value (that is, a value that is not NULL and not 0).
如果您使用非魔法值(即,非NULL且非0的值)更新另一个AUTO_INCREMENT列,则该值甚至不会更改。
You can both way 你们都可以
Using Eloquent Model 使用口才模型
$user = new Reports();
$user->email= 'johndoe@example.com';
$user->save();
$lastInsertId = $user->id;
Or 要么
Using Query Builder 使用查询生成器
$lastInsertId = DB::table('reports')->insertGetId(['email' => 'johndoe@example.com']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.