How do I get the MySQL autoincrement primary key from Sequelize on save()?(如何在 save() 上从 Sequelize 获取 MySQL 自动增量主键?)
本文介绍了如何在 save() 上从 Sequelize 获取 MySQL 自动增量主键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将新行插入 Sequelize,但无论我尝试什么,Sequelize 都不会返回刚刚保存的自动增量行的 ID.这是我的代码:
I am trying to insert new rows into Sequelize, but no matter what I try Sequelize does not return the ID of the autoincremented row that was just saved. Here's my code:
if (isDefined(jsonObject.id) && jsonObject.id == 0) {
let databaseObject = Database.getInstance().getModel(objectName).build(jsonObject);
//databaseObject.isNewRecord = true;
// Does not exist
//databaseObject.setNew(true);
transform.setNew(true);
transform.setJsonObject(jsonObject);
transform.setDatabaseObject(databaseObject);
return transform.populateJoins()
//.then(() => transform.baseMetadata())
//.then(() => transform.metadata())
.then(() => transform.baseExtract())
.then(() => transform.extract())
//.then(() => transform.clean())
.then(() => {
console.log('DATABASE OBJECT PRE SAVE: ');
console.log(transform.getDatabaseObject());
return transform.getDatabaseObject().save({
returning: true
});
}) // function () { return ; }
.then((data) => {
if (data instanceof sequelize.ValidationError) {
for (var field in data) {
this.addError(res.locals, ErrorCode.InvalidValue, field + ': ' + data[field]);
}
return false;
} else {
return Database.getInstance().getConnection().query('SELECT LAST_INSERT_ID();')
.then((row) => {
console.log('LAST INSERT ID: ');
console.log(row);
transform.getDatabaseObject().set('id', row[0]);
return transform.getDatabaseObject();
});
}
})
//.then(() => transform.getDatabaseObject()) // function () { return ; }
.then((data) => {
//console.log('Data is ' + typeof data);
console.log('NEW POST json: ');
console.log(jsonObject);
console.log('NEW POST data: ');
console.log(data);
console.log(data.get('id'));
if (jsonObject['id'] == data.get('id')) {
this.addError(res.locals, ErrorCode.InvalidValue, 'New object provided did not auto-increment.');
return false;
}
let dtoObject = {};
//for (var i in data.dataValues) {
// dtoObject[toCamelCase(i)] = data.get(i);
/
沃梦达教程
本文标题为:如何在 save() 上从 Sequelize 获取 MySQL 自动增量主键?
基础教程推荐
猜你喜欢
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01