Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
423 views
Welcome To Ask or Share your Answers For Others

1 Answer

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...