Where did you define the constraints regarding uniqueness of the data? PHP or database?
Bulk insert Many to Many
Hello,
FIrst post :-) I have an imported_products table, a categories table and a category_imported_product (with category and product_id) table.
I have a collection with 40.000 records with the following simplified structure
[category_id_1] -> multiple products
[category_id_2] -> multiple products
[category_id_3] -> multiple products etc.
I want to insert the collection into my imported products table. I have following code, but it is so slow. I think there is a much better way, but i can't find out. I use firstOrCreate, because of duplicate records in the collection.
foreach ($AllProductsFromDb as $categoryId => $importedProducts) {
foreach ($importedProducts as $importedProduct) {
$insertData = $importedProduct->toArray();
DB::transaction(function () use($insertData, $categoryId) {
$importedProduct = ImportedProduct::firstOrCreate(
['product_id' => $insertData['product_id']],
$insertData
);
$category = Category::find($categoryId)->first();
$importedProduct->categories()->save($category);
});
}
}
My first solution was a bulk insert, this is fast, but then i cannot insert the many to many relation for the category. Hopefully everything is clear...
Is there a better way? Thanks in advance :-)
Then you can cut down number of queries in half by replacing firstOrCreate with create.
Also no need to find category when you can achieve everything with $categoryId.
Use some of the following to create pivot records
$importedProduct->categories()->sync([$categoryId]);
$importedProduct->categories()->syncWithoutDetaching([$categoryId]);
$importedProduct->categories()->toggle([$categoryId]);
Give feedback once you try it. Maybe there is more. What is your current runtime for this?
Please or to participate in this conversation.