I have Files and Folders models that are related by a many-to-many relationship with a folder_file
pivot table.
I want to insert files in bulk using the insert() method, then use the list of inserted ids with the syncWithoutDetaching() method to update the pivot table, | first create the $data_array in a foreach loop that does other things as well:
$data_array = [];
foreach (...) {
// ...
$data_array[] = $row;
}
then I want to insert the data and update the pivot table:
File::insert($data_array);
$folder->files()->syncWithoutDetaching($array_of_inserted_ids);
Is it possible to get the list of inserted ids from the insert()
method?
Or maybe there is a more efficient way for better DB performance?
At first I just wanted to create the record and update the pivot table inside the foreach
loop that creates the $data_array
so that on every iteration it would create and update the tables, but that could be bad for performance with that many queries?
CodePudding user response:
You could use the createMany()
here. Instead of inserting the files then get the ids of inserted data. It will accept an array of data so that you could directly insert your array of files
then connecting them to the folder.
$folder->files()->createMany($data_array);