How to Insert Multiple Records using ResourceConnection in Magento 2

If you work with Magento 2 and need to insert multiple records into a database table, the ResourceConnection class is a useful tool that simplifies the process. This class enables you to connect to a database and execute various database operations.

To learn how to use ResourceConnection to insert multiple records into a table in Magento, follow the step-by-step guide mentioned below.

Let's assume you have a custom module named CustomModule_YourModule. In this example we'll insert multiple records in your_table_name table.

Inject the ResourceConnection class

In your custom module, you can inject the ResourceConnection class into your PHP class constructor to establish a database connection. For example, in a custom model class:

namespace CustomModule\YourModule\Model; use Magento\Framework\App\ResourceConnection; class YourModel { protected $resourceConnection; public function __construct(ResourceConnection $resourceConnection) { $this->resourceConnection = $resourceConnection; } public function insertMultipleRecords(array $data) { $connection = $this->resourceConnection->getConnection(); $tableName = $connection->getTableName('your_table_name'); $data = [ ['column1' => 'Value1', 'column2' => 'Value2'], ['column1' => 'Value3', 'column2' => 'Value4'], ]; $connection->insertMultiple($tableName, $data); } }

In the above code

  • $data should be an array of associative arrays, where each associative array represents a record to be inserted.
  • Update your table name with the proper prefix with this getTableName('your_table_name').

Replace 'column1', 'Value1', etc., with your actual data values.

That's it! You have now inserted multiple records into your custom database table using the ResourceConnection in Magento 2.

I hope this post helped you to find what you were looking for.

Bookmark it for your future reference. Do comment below if you have any other questions on that.

P.S. Do share this note with your team.

Review other articles maybe it'll help you too.

Recent Articles
Chrome Extension
Copyright © 2024 All rights reserved.
Ads OFF toggle_off