我正在使用 Sequelize 并且我正在尝试获取原始查询中最后插入的 ID.
I'm using Sequelize and I'm trying to get the last inserted ID in raw query.
我的查询是
.query(Sequelize.Utils.format(["insert into MyTable (field1, field2) values (?,?)", val1, val2])查询完成,但成功事件的结果为null.
The query is done perfectly, but the result on success event is null.
有人可以帮忙吗?
谢谢.
经过一些研究和无数次尝试,我了解了被调用对象在 sequelizeJs 中的工作原理.
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: '' }在这种情况下是参数名称"是将存储新 ID 的字段,sequelize 查找 __factory.autoIncrementField 以将最后插入的 id 的值设置为其值(__factory.autoIncrementField 的值).
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})这将导致这样的对象
{ __factory: { autoIncrementField: 'parameterName' }, parameterName: newInserted_ID }谢谢大家,我希望这可以帮助某人.
thanks for all, and I hope this can help someone.
推荐答案是的,您的答案奏效了.另一种方式是
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) }) })更多推荐
获取最后插入的 id Sequelize
发布评论