I am building the e-commerce application, I have struggled to this problem when save many of variants:
Supposedly, I got a request return the collection:
let data = {
"_token" :"{{ csrf_token() }}",
"data" : tableToJson($(".fixed-table table"), $(".scroll-table table")), // return data
}
let res = $.post(url, data);
It will result like this (in this case, I using with variant with 2 maximum options):
data = {
{
color: black,
size: 10,
sku: abxc,
quantity: 1,
price: 100$,
},
{
color: blue,
size: 10,
sku: abxz,
quantity: 2,
price: 1100$,
},
,....}
I intended to insert in controller with the function:
function insertVariant(Request $request) {
$datas = $request->all();
$id = options->insertGetId(
[
'name'=>'$data['color'] ,
]
,
[
'name'=>'$data['size'] ,
]
]);
foreach ($datas in $data) {
$options = new Options();
$sku = new SKU();
$sku['name'] = $data['sku'],
$sku['price'] = $data['price'],
$sku['quantity'] = $data['quatity']
$sku->save();
$variant_value = new VariantValue();
$variant_value['variant_options_id'] = $id[0];
$variant_value['value'] = $data['color'];
$variant_value['value'] = $data['size'];
$variant_value->save();
$sku_variant_value = new SKUVariantValues();
$sku_variant_value['variant_value_id'] = $variant_value->id;
$sku_variant_value['sku_id'] = $sku->id;
$sku_variant_value->save();
}
}
I see that request return too long as though its success?
how can I optimize when save multiple model in foreach with less cost as less as possible?
2
Answers
You are inserting data for every iteration its may take some time to store every insertsertion. First, need to prepare data in a single array. Then insert the data outside loop.
Assumption: I am assuming that all tables have auto-incremented id column(primary key)
Reference is taken from : Bulk insert and get returned ids laravel
Here is the code suggested by me:
Note: Read the comments inside the code carefully and work accordingly.