node.js 获取最后插入的 id Sequelize
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16723507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get last inserted id Sequelize
提问by ops.rio
I'm using Sequelize and I'm trying to get the last inserted ID in raw query.
我正在使用 Sequelize 并且我正在尝试获取原始查询中最后插入的 ID。
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.
查询完美完成,但成功事件的结果为null。
Can someone help?
有人可以帮忙吗?
Thanks.
谢谢。
Guys,
伙计们,
after some researches and zillions attempts, I understood how callee object work in sequelizeJs.
经过一些研究和无数次尝试,我了解了被调用对象在 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).
在这种情况下,“parameterName”是将存储新 ID 的字段,sequelize 查找 __factory.autoIncrementField 以使用其值(__factory.autoIncrementField 的值)将最后插入的 id 的值设置到属性中。
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.
谢谢大家,我希望这可以帮助某人。
采纳答案by Kamrul
Yes your answer is working. Another way would be
是的,你的答案是有效的。另一种方式是
var Sequelize = require("sequelize")
var sequelize = new Sequelize('test', 'root', 'root', {dialect: 'mysql'})
var Page = sequelize.define( 'page', {
type : {type: Sequelize.STRING(20)},
order : {type: Sequelize.INTEGER, defaultValue: 1}
},{
timestamps: false,
underscored: true
})
Page.__factory = {autoIncrementField: 'id'}
Page.id = ''
sequelize.query('INSERT INTO pages SET `type` = ?, `order` = ?, `topic_version_id` = ?', Page, {raw: false}, ['TEXT', 1, 1] ).success(function(page) {
console.log(page)
Page.find(page.id)
.success(function(result){
console.log(result)
})
})
回答by MiraGe
You have to add autoIncrement propertyin model definition.
您必须在模型定义中添加autoIncrement 属性。
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.
然后,您可以使用模型定义中的属性访问最后插入的 id。
Article.create(article)
.then(result => console.log(result.id));

