Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

node.js - Get last inserted id Sequelize

I'm using Sequelize and I'm trying to get the last inserted ID in raw query.

My query is

.query(Sequelize.Utils.format(["insert into MyTable (field1, field2) values (?,?)", val1, val2])

The query is done perfectly, but the result on success event is null.

Can someone help?

Thanks.


After some researches and zillions attempts, I understood how callee object work in sequelizeJs.

please, correct me if my answer is wrong.

the callee object needs this structure

{__factory:{autoIncrementField: 'parameterName'}, parameterName: '' }

in this case "parameterName" is the field that will store the new ID, sequelize looks for __factory.autoIncrementField to set value of last inserted id into property with its value (value of __factory.autoIncrementField).

so, my call to querys method would be

.query(sequelize.Utils.format(tempInsert), {__factory:{autoIncrementField: 'parameterName'}, parameterName: '' }, {raw: true})

this will result in object like that

{ __factory: { autoIncrementField: 'parameterName' }, parameterName: newInserted_ID }

thanks for all, and I hope this can help someone.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have to add autoIncrement property in model definition.

const Article = sequelize.define('articles', {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true
  }, {},
  {
   createdAt: false,
   updatedAt: false
  });

Then, you can access last inserted id with property in model definition.

Article.create(article)
  .then(result => console.log(result.id));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...