Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to you get the last inserted ID with a raw query using Sequelize?

When trying the following raw MySQL insert in sequelize.js:

mysql_sequelize.query( 'INSERT IGNORE INTO steamer(steamer_id, prov_id, name, avatar) VALUES(UNHEX(REPLACE(UUID(),\'-\',\'\')), \'' + prov_id + '\', \'' + steamer_name + '\', \'' + steamer_avatar + '\')')
  .then(function (data) {
       console.log('inserted STEAMER data---> ',data);  // no useful info
  });
);

The resulting console log looks like the following:

inserted STEAMER data--->  [ OkPacket {
    fieldCount: 0,
    affectedRows: 1,
    insertId: 0,
    serverStatus: 2,
    warningCount: 1,
    message: '',
    protocol41: true,
    changedRows: 0 },
  OkPacket {
    fieldCount: 0,
    affectedRows: 1,
    insertId: 0,
    serverStatus: 2,
    warningCount: 1,
    message: '',
    protocol41: true,
    changedRows: 0 } ]

What do I have to do to get following data's ID? or even the last inserted ID?

like image 556
Brandon Minton Avatar asked Feb 28 '16 23:02

Brandon Minton


1 Answers

You can achieve this by passsing { type: sequelize.QueryTypes.INSERT } as a option argument. This will make sequelize return the insert it.

Simple query example:

sequelize.query(
    "INSERT INTO clients (name) values ('myClient')",
    { type: sequelize.QueryTypes.INSERT }
).then(function (clientInsertId) {
    console.log(clientInsertId);
});
like image 63
lin Avatar answered Oct 19 '22 13:10

lin