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
Anshu Mishra
8,9907 gold badges42 silver badges88 bronze badges
-
2Try 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– Abdul2018年03月27日 09:35:33 +00:00Commented Mar 27, 2018 at 9:35
1 Answer 1
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
Prince Patel
23.1k10 gold badges102 silver badges124 bronze badges
-
How can we update here if the record is exist?Jafar Pinjar– Jafar Pinjar2019年11月07日 12:00:58 +00:00Commented 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::insertArrayPrince Patel– Prince Patel2019年11月07日 12:17:19 +00:00Commented Nov 7, 2019 at 12:17
-
it's working fine. but if run again it will insert duplicate records. how to check and insert.Nishan than– Nishan than2021年08月02日 13:49:51 +00:00Commented Aug 2, 2021 at 13:49
default