Last active
June 30, 2020 07:25
-
-
Save artze/6dc1107579247bd8bb9cc773e50d9a31 to your computer and use it in GitHub Desktop.
Upsert with Knexjs and MySQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const insert = knex('tableName').insert({ | |
...newObj, | |
id: uuidv4(), | |
created_at: knex.fn.now(), | |
updated_at: knex.fn.now() | |
}); | |
// create string of raw update column parameters (e.g. field1=value1, field2=value2) | |
const rawUpdateParameters = Object.keys(updateObj) | |
.map((field) => `${field}=${updateObj[field]}`) | |
.join(', '); | |
knex.raw('? ON DUPLICATE KEY UPDATE ?', [ | |
insert, | |
knex.raw(rawUpdateParameters) | |
]); | |
// The raw query essentially translates to MYSQL query: | |
// INSERT INTO tableName VALUES (x, y) | |
// ON DUPLICATE KEY UPDATE field1=value1, field2=value2; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think that string values should be enclosed by single quotes to avoid MySQL's ER_BAD_FIELD_ERROR error.
Thank you for your good knowledge.