Skip to content

Instantly share code, notes, and snippets.

@artze
Last active June 30, 2020 07:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artze/6dc1107579247bd8bb9cc773e50d9a31 to your computer and use it in GitHub Desktop.
Save artze/6dc1107579247bd8bb9cc773e50d9a31 to your computer and use it in GitHub Desktop.
Upsert with Knexjs and MySQL
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;
@munierujp
Copy link

munierujp commented Jun 29, 2020

I think that string values should be enclosed by single quotes to avoid MySQL's ER_BAD_FIELD_ERROR error.

const record = {
  foo: 'foo',
  bar: "It's bar"
}

const insert = knex.insert(record).into('tableName')

const values = Object.entries(record)
    .map(([column, value]) => db.raw('?? = ?', [column, value]))
    .join(', ')

const query = db.raw(`${insert} ON DUPLICATE KEY UPDATE ${values}`)

console.log(query.toString())
insert into `tableName` (`bar`, `foo`) values ('It\'s bar', 'foo') ON DUPLICATE KEY UPDATE `foo` = 'foo', `bar` = 'It\'s bar'

Thank you for your good knowledge.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment