Insert Multiple Records in Magento 2

Insert Multiple Records in Magento 2 Using insertMultiple()

If you’re looking to insert multiple records into a database table, Magento 2 provides a powerful function known as insertMultiple().

Magento 2 offers the insertMultiple() function as a robust solution for efficiently inserting multiple records into a database table. This can significantly enhance the performance of your custom modules when handling a large volume of data

In this blog, I will explain the steps to leverage the insertMultiple() function in Magento 2 for inserting multiple records into a table.

 

Step 1: Module Setup

First things first, ensure that you have your custom module set up in your Magento 2 installation.If you’re unsure how to create a basic module structure,  Check how to Create a Module in Magento 2 to create a new module.

Step 2: Create Helper class to insert multiple records

For this tutorial I am creating one helper class. In which we will write the function to insert multiple records in table.

namespace Rk\CustomModule\Helper;

use Magento\Framework\App\ResourceConnection;

class Data
{

    /**
     * @var \Magento\Framework\DB\Adapter\AdapterInterface
     */
    protected $connection;

    /**
     * @var Resource
     */
    protected $resource;

    /**
     * @param \Magento\Framework\App\ResourceConnection $resource
     */
    public function __construct(
        ResourceConnection $resource
    ) {
        $this->connection = $resource->getConnection();
        $this->resource = $resource;
    }

    /**
     * Insert multiple records
     *
     * @param array $data
     */
    public function insertRecords($data, $tableName)
    {
        $tableName = $this->resource->getTableName(self::TABLE_NAME);
        return $this->connection->insertMultiple($tableName, $data);
     }
}

Step 3: Prepare Data 

Now, you can use above function when it is required to add multiple records. Prepare your Data in below mentioned format.

foreach($multipleRecords as $record) {
    $data[] = [
        'field1' => $record['field1'],
        'field2' => $record['field2']
    ];
}
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$helper = $objectManager->get('Rk\CustomModule\Helper\Data');
$helper->insertRecords($data, 'TABLE_NAME');

 

Note: For demo purpose I have used Objectmanager to get the class object. Inject the class in constructor when it’s required.

 

Checkout Custom SQL Query for other useful function for SQL queries

 

Hope you find this Tutorial is helpful. Do comment if you face any issue or Contact me If you want any help or customization in your existing Project or Extension.

Leave a Reply

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

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top