serverless-mysql icon indicating copy to clipboard operation
serverless-mysql copied to clipboard

How to get inserted ids from mutlitple values in a transaction?

Open carlosfer02 opened this issue 4 years ago • 1 comments

I am tring to insert multiple values inside query statement of a transaction. I need to get the inserted ids for the next query chain, how can i retrieve them?

let results = await mysql.transaction()
            .query('INSERT INTO boxes (branch_id, number) VALUES (1,1), (1,2), (1,3)')
            .query(async (r) => {
                //Here i need to get the boxes ids...
            })
            .rollback(e => {})
            .commit();

carlosfer02 avatar Mar 28 '21 15:03 carlosfer02

Is this what you want? @carlosfer02

const results  =  await  mysql . transaction( ) 
  . query ( 'INSERT INTO test (x) VALUES (?)' ,  [ 1 ] ) 
  . query ( ( r )  =>  [ 'UPDATE table SET x = 1 WHERE id =?' ,  r . insertId ] ) 
  . commit ( ) 

code-xhyun avatar May 06 '21 06:05 code-xhyun

@devShHong

Same problem. I am inserting a bunch of items. New ids of these items I need for another table. But I am getting only one object inserted instead of an array of objects.

pergunt avatar Oct 05 '22 11:10 pergunt

@pergunt sry dude, It's been a long time since I've used that library, so i can't say proper information.

code-xhyun avatar Oct 06 '22 08:10 code-xhyun

Here we go....

import mysql from 'serverless-mysql';
import {raw} from "mysql";

const db = mysql({....});

const inserts1 = [['Foo'], ['Bar']];
const inserts2 = [[42, raw(`(SELECT id FROM names WHERE name=${db.escape('Foo')})`)],[69, raw(`(SELECT id FROM names WHERE name=${db.escape('Bar')})`)]];

try {
    const results = await db.transaction()
      .query('TRUNCATE prices')
      .query('ALTER TABLE prices DROP FOREIGN KEY FK_PricesNames')
      .query('TRUNCATE names')
      .query('INSERT INTO name (name) VALUES ?', [inserts1])
      .query('INSERT INTO prices (price, `name-id`) VALUES ?', [inserts2])
      .query('ALTER TABLE prices ADD CONSTRAINT `FK_PricesNames` FOREIGN KEY (`name-id`) REFERENCES `names` (`id`) ON DELETE RESTRICT ON UPDATE NO ACTION')
      .commit();
    await db.end();
    return results;
  } catch (error) {
    return {error};
  }

votemike avatar Apr 24 '23 07:04 votemike