You can create custom insert query using Magento 2 to add/create a new record in database table via ResourceConnection class.
Using the Insert query, You can add a new record to the table using direct SQL query insert() without going to model operation.
Let’s we are adding a new record in sales_order_status table, that contains two columns only status and label
<?php
namespace Path\To\Class;
use Magento\Framework\App\ResourceConnection;
class addOrderStatus {
const ORDER_STATUS_TABLE = 'sales_order_status';
const STATUS_FIELD = 'status';
const STATUS_LABEL_FIELD = 'label';
/**
* @var ResourceConnection
*/
private $resourceConnection;
public function __construct(
ResourceConnection $resourceConnection
) {
$this->resourceConnection = $resourceConnection;
}
/**
* insert Sql Query
*/
public function insertStatus()
{
$connection = $this->resourceConnection->getConnection();
$tableName = $connection->getTableName(self::ORDER_STATUS_TABLE);
$data = [
self::STATUS_FIELD => 'pending_hold',
self::STATUS_LABEL_FIELD => __("Pending Onhold"),
];
$connection->insert(self::ORDER_STATUS_TABLE, $data);
}
}
The First argument is the table name.
The Second argument is an array of columns of table.
The output is the new row added to sales_order_status table. You can add any no. of record in any table using insert() query.
Check for other Direct Sql Query in Magento 2
.

One Reply to “Add record using insert query in Magento 2.”