Save array of objects in one mysql query Hi!
How can I insert in mysql the following array of objects in one query using eloquent or query builder?
[
{
"name": "John",
"surname": "Doe"
},
{
"name": "Jane",
"surname": "Doe"
},
{
"name": "John",
"surname": "Dean"
}
]
Thank you!
Hi!
Thanks for your response! I tried the saveMany and createMany methods but they give me an error:
Call to undefined method App\Models\MyModel::saveMany()
I am trying to save in a mysql table an array of objects, like the one I posted in the question, returned by an API call.
Do you know an efficient way to do it in Laravel?
Thanks for your help!
Would you mind showing the codes?
@rimicsani
Do you have the relationship set up with the correct tables?
Read doc's that @frankielee gave you the link.
Hi!
I don't have (and I don't need) relationships for that table. It has just to be filled with data that come from an API call, nothing else.
Thanks!
@rimicsani
You want to insert the entire array into one record?
@lemmon In many records.
I was wondering if there is a Laravel helper method to insert the entire array, in multiple records, in one query
Thanks!
@michaloravec thanks!
I guess I have to loop through each of them or do you have a suggestion about how to convert those objects efficiently?
$data = collect($data)->map(function ($item) {
return (array) $item;
})->toArray();
Hi @michaloravec ! I tried your method but it doesn't convert. The objects inside the array all have the same structure as I described in the question.
Thanks a lot!
Well, there's nothing I can do.
Problem solved! Thank you much!
Please sign in or create an account to participate in this conversation.