0

I want insert multiple record without for loop in Magento 2 my data is as follow,

Array
(
    [0] => Array
        (
            [path] => whatsapp_contact/whatsapp_contact_button_settings/info_button_click
            [field_data] => Click one of our representatives below to chat on WhatsAppFrom Admin
            [form_key] => Rcs1nNj5OzkBwuK4
        )

    [1] => Array
        (
            [path] => whatsapp_contact/whatsapp_contact_button_settings/info_button_click
            [field_data] => 
            [form_key] => Rcs1nNj5OzkBwuK4
        )

    [2] => Array
        (
            [path] => whatsapp_contact/whatsapp_contact_button_settings/info_button_click
            [field_data] => 
            [form_key] => Rcs1nNj5OzkBwuK4
        )

    [3] => Array
        (
            [path] => whatsapp_contact/whatsapp_contact_button_settings/info_button_click
            [field_data] => 
            [form_key] => Rcs1nNj5OzkBwuK4
        )

)

need to insert at once without for loop using collection

enter image description here

1
2

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);

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.