Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get record ids after bulk insert in laravel

I'm using laravel 5.4 I want to get record ids after I insert them in the table. here's data that I want to insert, it stored in array

$data = [
  [
    "count" => "100",
    "start_date" => 1515628800
  ],
  [
    "count" => "102",
    "start_date" => 1515715200
  ]
];

here I insert the array of items at once

\Auth::user()->schedule()->insert($data);

but this method returns boolean and I want to get ids(or all columns) of these new items after they been inserted, how should I do this? it doesn't matter if it will be done with eloquent or querybuilder. I already tried insertGetId method, but it doesn't seem to work with multidimensional array. if its not possible with laravel, what would be the best way to implement this?

like image 362
devnull Ψ Avatar asked Jan 11 '18 13:01

devnull Ψ


1 Answers

Workaround: Select highest PK value and you should know what values they had. You might need locking to prevent a race with other users though.

edit:

LOCK TABLES schedule WRITE;

// Select last ID

UNLOCK TABLES;

the list of id's is then the last id - insert count

like image 177
online Thomas Avatar answered Oct 21 '22 23:10

online Thomas