laravel 如何在laravel中获取最后插入的ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35521277/
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 ids in laravel
提问by Believe It or Not
I am inserting multiple rows at the same time, say 2 rows
我同时插入多行,比如说 2 行
$multiple_rows = [
['email' => '[email protected]', 'votes' => 0],
['email' => '[email protected]', 'votes' => 0]
];
DB::table('users')->insert($multiple_rows);
How can I get those inserted ids.
我怎样才能得到那些插入的 id。
I am doing it, this way for now.
我正在这样做,现在就这样。
foreach($multiple_rows as $row){
DB::table('users')->insert($row);
$record_ids[] = DB::getPdo()->lastInsertId();
}
Any other good way to do it, without inserting single row each time.
任何其他好的方法来做到这一点,而无需每次插入单行。
回答by user2094178
You could do something like the following:
您可以执行以下操作:
$latestUser = DB::table('users')->select('id')->orderBy('id', 'DESC')->first();
$multiple_rows = [
['email' => '[email protected]', 'votes' => 0],
['email' => '[email protected]', 'votes' => 0]
];
DB::table('users')->insert($multiple_rows);
$users = DB::table('users')->select('id')->where('id', '>', $latestUser->id)->get();
回答by Renjith V R
If you really need all the inserted ID's
如果你真的需要所有插入的 ID
$dataArray = [
['name' => 'ABC'],
['name' => 'DEF']
];
$ids = [];
foreach($dataArray as $data)
{
$ids[] = DB::table('posts')->insertGetId($data);
}
To get all id with a massive insertion I think the good way is to first get the last id in the table, make the massive insertion and get the last id. In theory they must follow, unless there has been an insertion from another connection. To avoid that the solution is a transaction.
要通过大量插入获取所有 id,我认为最好的方法是首先获取表中的最后一个 id,进行大量插入并获取最后一个 id。理论上它们必须遵循,除非有来自另一个连接的插入。为避免这种情况,解决方案是事务。
Update
更新
Also read the documentation
另请阅读文档