最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to you get the last inserted ID with a raw query using Sequelize? - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Feb 28, 2016 at 23:13 Brandon Minton asked Feb 28, 2016 at 23:04 Brandon MintonBrandon Minton 1,0144 gold badges15 silver badges26 bronze badges 1
  • 1 year later, sorry Iam late :D – lin Commented Apr 25, 2017 at 16:23
Add a ment  | 

1 Answer 1

Reset to default 6

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);
});
发布评论

评论列表(0)

  1. 暂无评论