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?

7ochem
7,61516 gold badges54 silver badges82 bronze badges
asked Mar 27, 2018 at 9:27
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); 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);
answered Mar 27, 2018 at 10:49
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

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.