Get record ids after mass insert in laravel

I am using laravel 5.4 I want to get the record identifiers after I insert them into the table. here the data i want to insert is stored in an array

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

here I immediately insert an array of elements

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

but this method returns boolean, and I want to get the identifiers (or all columns) of these new elements after they are inserted, how can I do this? it doesn't matter if this is done with eloquentor querybuilder. I already tried the method insertGetId, but it does not work with a multidimensional array. if this is not possible with laravel, what would be the best way to implement this?

+4
source share
3 answers

: PK, , . , , .

:

LOCK TABLES WRITE;

//

;

- last id - insert count

+1

. , :

$scheduleIds[] = auth()->user()->schedule()->insertGetId($data);

:

$scheduleIds[] = auth()->user()->schedule()->create($data)->id;
0

You can set custom functions that return what you need

public function insertGetIdArray($object, $data){
   $result = [];
   foreach($data as $d){
       array_push($result, $object->insertGetId($d));
   }
   return $result;
}

and then name it like this:

$results = $this->insertGetIdArray(\Auth::user()->schedule(), $data);

You could also be like a fantasy and make your own class to better handle the action more encapsulated

0
source

Source: https://habr.com/ru/post/1692047/


All Articles