如何在 Laravel 中获取最后插入的 ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37969332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get last inserted id in Laravel?
提问by Bhavin Shah
Here is my code
这是我的代码
$users = DB::table('users')->insert(array(
'email_id' => $email_id,
'name' => $name,
));
$lastInsertedID = $users->lastInsertId();
return $lastInsertedID;
I want to get last inserted id for particular record. I have tried using Eloquent ORM. but it didn't work.
我想获取特定记录的最后插入的 ID。我曾尝试使用 Eloquent ORM。但它没有用。
Any help would be grateful.
任何帮助将不胜感激。
Thank You.
谢谢你。
回答by aynber
Use insertGetId()
$id = DB::table('users')-> insertGetId(array(
'email_id' => $email_id,
'name' => $name,
));
回答by Majbah Habib
Follow the code to get last inserted id by using ->insert()
按照代码使用 ->insert() 获取最后插入的 id
$lastInsertedID = DB::table('users')
->insert( array(
'email_id' => $email_id,
'name' => $name
)
)
->lastInsertId();
回答by yekyawaung
Do you mean you inserted record id? You can get the following way:
你的意思是你插入了记录ID?您可以通过以下方式获得:
//UserController.php
//用户控制器.php
$user = new User;
$user->name = $request->name;
$user->email = $request->email;
if($user->save()){
echo "User's record id is ".$user->id; *//$user->id is your lastest record id*
}