A simple question with a surprisingly elusive answer... In my application I use DB::insert() to mass insert up to potentially thousands of records at once. However, I then need to know the ids of the newly inserted records so that I can then also insert related models. Since the DB::insert() function itself only returns a boolean, how can I retrieve these records? (Bear in mind that these insertions can sometimes happen in parallel, so simply using created_at or take to retrieve the last X number of records is not reliable)
#How to retrieve records created by DB::insert(...)
13 messages · Page 1 of 1 (latest)
Potential solution: #general message
Can you not just use Model::insert() ?
or is it just that it still doesn't return the hydrated models?
Yeah that just returns true as well
I think it's one of those trade-off situations where, faster inserts are possible because of bulk inserting, but the entire reason it's faster is because of this
the only thing i can think of, is to insert a reference manually to each one that you can keep in memory and query on
Does your related data not have anything relating back to the original data that you can query on?
Can you batch insert your thousands of rows somewhere, in full, temporarily, then process them to add the relationships later.
What about, adding a batch_id generated using Str::uuid that you can then reliably query for
Add that same batch id to each entry in the batch, insert them, then run MyModel::where('batch_id', $uuid)-get()