4 (79.3%) 57 votes

 

In this article I will show you a good performance solution to to Insert/Update Multiple Records to Database in Magento 2. In my example, I create a new table in Mysql: my_custom_table with two fields:

  • id: primary key, item Id
  • qty: int(11), the number of item

In Magento 2, almost the Records  have some changes in Database in Magento 2.    Insert/Update Multiple Records to Database in Magento 2 now have a bit different from Magento first version.  And of course, you must learn about it.

How to Insert/Update Multiple Records to Database in Magento 2

  • Normally you can update multiple records in database using save() method of Model.

  • However, this solution is not recommended because its performance is not good. You can see that the save() function has been called in a loop. I found another solution to solve this issue. I write the commands below in my resource model.
    • /app/code/[NameSpace]/[ModuleName]/Model/ResourceModel/Custom.php

  • I have another example for inserting multiple records. I also write it in my custom resource model.
    • /app/code/[NameSpace]/[ModuleName]/Model/ResourceModel/Custom.php

The performance of this solution is better than using save() method of Model in a loop. Another advantage is that using MySQL transaction. If there is any issue while saving one of the records to the database, all the previous records will be rollbacked. Then nothing is changed in the database.

This is all the things you must do when you want to  Insert/Update Multiple Records to Database in Magento 2. Learn about Insert/Update Multiple Records to Database in Magento 2 become really helpful when you manage your store.

Good luck to you with your ecommerce. Thanks for reading!

Your Magento website needs a powerful Magento ERP for stock control.

DON'T MISS THE CHANCE!

magento erp

How to Add More Variable to Window.checkoutConfig in Magento Checkout
How to Create a Module in Magento 2

Leave a Reply

Your email address will not be published. Required fields are marked *