Core: How to reproduce the algorithm ON DUPLICATE KEY UPDATE?

Created on 19 Mar 2017  路  11Comments  路  Source: adonisjs/core

I have a table with users options:

|    id     |    option_id     |    option_value     |
------------------------------------------------------

I want to update a row in a table with one command or create a new one if it does not already exist.

INSERT INTO
  options
SET
  option_id = 'enabled',
  value = 1
ON DUPLICATE KEY UPDATE
  value = 1

How to achieve this result using Lucid or Query Builder?

Most helpful comment

I think that having a insertOrUpdate method could be a good idea, and would simplify certain usecases.

All 11 comments

You can run a raw query.

Database.schema.raw('Your sql query')

@thetutlage, There is no way to call a method? For example

Database.table('options').insertOrUpdate({option_id: 'enabled', ...})

Hey @cawa-93!

There's the save() method.

For this, as I understood, you must first find the object. If it does not exist, create. Then save. This requires a few more requests and manipulations, rather than a simple insertOrUpdate (In perspective)

May I ask what's your usecase?

@RomainLanz, Excuse me, but I did not understand what you mean

I think that having a insertOrUpdate method could be a good idea, and would simplify certain usecases.

For those who are also interested in this issue, I propose a temporary solution (for mysql):

const pagesData = {
  id: 1,
  name: 'Some page',
  picture: 'https://...',
}
const insert = Database.table('pages').insert(pagesData).toString()
yield Database.schema.raw(insert + ' ON DUPLICATE KEY UPDATE name=VALUES(name), picture=VALUES(picture), update_at=CURRENT_TIMESTAMP')

Closing since not a bug, but can be discussed in forum.https://forum.adonisjs.com/

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

douglaszaltron picture douglaszaltron  路  3Comments

GianCastle picture GianCastle  路  3Comments

themodernpk picture themodernpk  路  3Comments

devcaststudio picture devcaststudio  路  3Comments

begueradj picture begueradj  路  3Comments