我有一个模型,Case.js:
...
attributes: {
id: {
type: 'integer',
unique: true,
primaryKey: true,
columnName: 'pid' //an auto-increment primary key, generated by MySQL
},
...
}
我想在创建后获取这个 id:
Case.create({...}).then(function(aCase){
console.log(aCase.id);
})
创建成功,但我得到的输出是未定义的。 我尝试将 autoPK 设置为 false,并删除“unique”和“primaryKey”条目,但结果没有改变。 请告诉我如何让 create() 返回这个 id。
最佳答案
我自己已经解决了。问题出在我的模型 Case.js 中。 在 sails.js 中,如果您希望在 create() 之后返回 MySQL 创建的自动增量主键(通常是 id),您的模型应如下所示:
module.exports = {
...
autoPK: false,
attributes: {
id: {
type: 'integer',
unique: true,
primaryKey: true,
autoIncrement: true,
},
...
}
}
注意“autoIncrement”属性,在我的情况下是必要的,并且可能在每个自动增量主键中都是必要的。
关于mysql - 在 sails.js 中创建后如何让 create() 返回自增主键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43648523/