5

Following code is working fine.

$data = $this->_customDataSave->create();
$data->setUsername($this->getUsername());
$data->setFullname($this->getFullname());
$data->setEmail($this->getEmail());
$data->save();

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?

1
  • 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
    Commented Mar 27, 2018 at 9:35

1 Answer 1

18

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) {
       //Error
    }
}

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);
3
  • How can we update here if the record is exist? Commented Nov 7, 2019 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 Commented Nov 7, 2019 at 12:17
  • it's working fine. but if run again it will insert duplicate records. how to check and insert. Commented Aug 2, 2021 at 13:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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