Use of insertMultiple mysql query in Magento 2.

Write a Mysql insertMultiple query using Magento’s standard way to insert multiple rows/records at a single time.

You can write direct SQL query insertMultiple() without worrying about the Model operation for inserting multiple records in a specific table using below code snippet.

Return Type: insertMultiple() always returns an integer number for affected rows in a table.

Base Definition of function:

/**
 * Inserts a table multiply rows with specified data.
 *
 * @param mixed $table The table to insert data into.
 * @param array $data Column-value pairs or array of Column-value pairs.
 * @return int The number of affected rows.
 */
public function insertMultiple($table, array $data);

Let’s we are writing a query from the sales_order_status table to accomplish the insertMultiple() query operation.

Table sales_order_status contains two fields only, status and label.

<?php
namespace Jesadiya\SelectQuery\Model\ResourceModel;

use Magento\Framework\App\ResourceConnection;

class Data
{
    private const ORDER_TABLE = 'sales_order_status';
    private ResourceConnection $resourceConnection;

    public function __construct(
        ResourceConnection $resourceConnection
    ) {
        $this->resourceConnection = $resourceConnection;
    }

    /**
     * Insert multiple records SQL Query
     *
     * @return int
     */
    public function insertMultipleQuery()
    {
        $connection = $this->resourceConnection->getConnection();
        
        $tableName = $connection->getTableName(self::ORDER_TABLE);

        $data = [
            ['status' => 'pending', 'label' => 'Pending'],
            ['status' => 'processing', 'label' => 'Processing']
        ];

        return $connection->insertMultiple($tableName, $data);
    }
}

Output:
2 (No. Of Inserted Records.)

You can see new records are added to the sales_order_status table.

Check for Other Direct SQL Query in Magento 2