简体   繁体   中英

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?

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM