How to insert multiple records into a table without a model?

Hello folks, welcome back to my blog. In this article, I give you a sample code to insert multiple records into a table.

Normally we use the repository, resource model to save records. But it will be good for a single record. If we have bulk data and save data with foreach it will become a memory hunter. The easiest solution is to use insertMultiple function of class Magento\Framework\App\ResourceConnection

Sample Code:

namespace Mageprince/SampleModule/Model;

class InsertData
{
    protected $connection;

    protected $resource;

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

    public function insertBulkData($table, $data)
    {
        try {
            $tableName = $this->resource->getTableName($table);
            return $this->connection->insertMultiple($tableName, $data);
        } catch (\Exception $e) {
        //Error
        }
    }
}

Use above insertMultiple function to insert bulk data

$records = [] // All records
$bulkInsert = []; // Insert data

foreach($records as $record) {
    $bulkInsert[] = [
        'user_name' => $record['user_name'],
        'email' => $record['email']
    ];
}

$this->insertBulkData('my_table_name', $bulkInsert);

You can avoid saving multiple data in foreach by using insertMultiple function.

Feel free to comment below if you have any questions.

Keep sharing 🙂