Following code is working fine.

$data = $this->_customDataSave->create();

But I need to execute this piece of code in the loop to insert multiple of rows of data.
I don't want to call save inside loop.
How can I do that without calling save inside loop?

  • 2
    Try this: $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $resource = $objectManager->get('Magento\Framework\App\ResourceConnection'); $connection = $resource->getConnection(); $tableName = $resource->getTableName('mytest'); $connection->insertMultiple($tableName, $rowsData); – Abdul Mar 27 '18 at 9:35

Use insertMultiple function of class Magento\Framework\App\ResourceConnection

protected $connection;

protected $resource;

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

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

Now you can use insertMultiple() function like

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

$this->insertMultiple('my_table', $bulkInsert);
| improve this answer | |
  • How can we update here if the record is exist? – jafar pinjar Nov 7 '19 at 12:00
  • @jafarpinjar I just deep into the code and found that insertArray() function use REPLACE strategy. Please check with passing PRIMARY KEY in bulk insert. Please check this for more: \Magento\Framework\DB\Adapter\Pdo\Mysql::insertArray – Prince Patel Nov 7 '19 at 12:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.