如何在 sails.js 中创建后创建 create() return 自增主键?
How to get create() return auto-increment primary key after creation in sails.js?
我有模型,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() return 这个 id.
我正在查看 Sails.js documentation 以在数据库中创建新条目。方法表示为
Something.create(values).exec(function (err, records) {
});
在你的情况下,你应该
Case.create({...}).exec(function(err, aCase){
console.log(aCase.id);
})
我自己解决了。问题出在我的模型Case.js。
在 sails.js 中,如果你想在 create() 之后返回由 MySQL 创建的自增主键(通常是 id),你的模型应该如下所示:
module.exports = {
...
autoPK: false,
attributes: {
id: {
type: 'integer',
unique: true,
primaryKey: true,
autoIncrement: true,
},
...
}
}
注意 "autoIncrement" 属性,在我的情况下是必需的,并且可能在每个自增主键中都是必需的。
我有模型,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() return 这个 id.
我正在查看 Sails.js documentation 以在数据库中创建新条目。方法表示为
Something.create(values).exec(function (err, records) {
});
在你的情况下,你应该
Case.create({...}).exec(function(err, aCase){
console.log(aCase.id);
})
我自己解决了。问题出在我的模型Case.js。 在 sails.js 中,如果你想在 create() 之后返回由 MySQL 创建的自增主键(通常是 id),你的模型应该如下所示:
module.exports = {
...
autoPK: false,
attributes: {
id: {
type: 'integer',
unique: true,
primaryKey: true,
autoIncrement: true,
},
...
}
}
注意 "autoIncrement" 属性,在我的情况下是必需的,并且可能在每个自增主键中都是必需的。