How to get last inserted ids in laravel

為{幸葍}努か 提交于 2019-11-27 08:19:20

问题


I am inserting multiple rows at the same time, say 2 rows

$multiple_rows = [
    ['email' => 'taylor@example.com', 'votes' => 0],
    ['email' => 'dayle@example.com', 'votes' => 0]
];
DB::table('users')->insert($multiple_rows);

How can I get those inserted ids.

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.


回答1:


You could do something like the following:

$latestUser = DB::table('users')->select('id')->orderBy('id', 'DESC')->first();

$multiple_rows = [
    ['email' => 'taylor@example.com', 'votes' => 0],
    ['email' => 'dayle@example.com', 'votes' => 0]
];

DB::table('users')->insert($multiple_rows);

$users = DB::table('users')->select('id')->where('id', '>', $latestUser->id)->get();



回答2:


If you really need all the inserted ID's

$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.

Update

Also read the documentation



来源:https://stackoverflow.com/questions/35521277/how-to-get-last-inserted-ids-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!