How to use insertOnDuplicate query in Magento 2.

Use of insertOnDuplicate query using Magento 2,  You need to create a Connection object first to run the query using ResourceConnection class.

When you insert any new row into a table if the row causes a duplicate in the Primary key or UNIQUE index, throw an error in MySQL.

Base Definition of function:

/**
 * Inserts a table row with specified data.
 *
 * @param mixed $table The table to insert data into.
 * @param array $data Column-value pairs or array of column-value pairs.
 * @param array $fields update fields pairs or values
 * @return int The number of affected rows.
 */
public function insertOnDuplicate($table, array $data, array $fields = []);

Example,

<?php

namespace Your\PathTo\Model;

use Magento\Framework\App\ResourceConnection;

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

    /**
     * InsertOnDuplicate SQL Query
     */
    public function insertOnDuplicateQuery()
    {
        $connection  = $this->resourceConnection->getConnection();
        $tableName = "Your_TableName";

        $data = ["column_name1" => "value1", "column_name2" => "value2"]; // Key_Value Pair

        return $connection->insertOnDuplicate($tableName, $data, []);
    }
}

The first

 argument is tableName

The second

 argument is the key-value pair of an array.

The third

 argument is optional for the table's field of array. (update fields pairs column name)

Check for other Direct SQL Query in Magento 2