R
R
Ruslan Ruslanov2019-06-07 12:04:31
Yii
Ruslan Ruslanov, 2019-06-07 12:04:31

How to properly style INSERT ... ON DUPLICATE KEY UPDATE?

mariadb, yii2, how to properly style INSERT ... ON DUPLICATE KEY UPDATE?
tried like this:

\Yii::$app->db->createCommand()
    ->batchInsert(ProductsBarcodes::tableName(), ['product_code', 'barcode'], $barcodes_codes)
    ->execute();

mistake:
Error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '4064900053098' for key 'barcode'

I googled it, reread it, I'm trying to make a query using queryBuilder like this (taken from here ):
$db = \Yii::$app->db;
$sql = $db->queryBuilder->batchInsert(ProductsBarcodes::tableName(), ['product_code', 'barcode'], $barcodes_codes);
$db->createCommand($sql . ' ON DUPLICATE KEY UPDATE')->execute();

throws an error:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1
The SQL being executed was: INSERT INTO `product_barcode` (`product_code`, `barcode`) VALUES ('123123', '123123123'), ('1005770', '873293005560'), ('1006274', '8001090190543'), ('1006275', '4015400681243'), ('1006276', '4015400681212'), ('1006277', '4606086374538') ON DUPLICATE KEY UPDATE

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Ruslan Ruslanov, 2019-06-07
@dasauser

I did this:
1. I look for a record with the necessary attributes in the database
2. if there is - I skip it, if not - I add it to the array of updated records
3. I create a query that inserts records

A
AUser0, 2019-06-07
@AUser0

If MySQL - then instead of INSERT INTO you can do REPLACE INTO, all query arguments are the same, only the first word changes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question