mysql - 在 sails.js 中创建后如何让 create() 返回自增主键?

标签 mysql 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() 返回这个 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/

相关文章:

mysql - MySQL 存储函数中确定的奇怪 session 变量值

MySQL 自动递增 : Is there any way to reassign IDs starting from 1?

node.js - 风 sails : how to redirect after creating a model with the built-in crud operations?

mysql - 从子表中选择计数

Mysql InnoDB表到elasticsearch : ON UPDATE CURRENT TIMESTAMP inside transaction

mysql - 存储过程中“字段列表”中的未知列

node.js - 使用 Sails.js 和 OrientDB 进行多边建模

node.js - 如何在 sails js 中配置 Node 推送服务器?

javascript - 在输入类型 = 文件中没有选择文件的情况下提交表单超时

javascript - 在 Sails 中使用多个 unirest 请求