【问题标题】:Knex primary key auto incrementKnex 主键自动递增
【发布时间】:2017-02-10 10:17:47
【问题描述】:

我正在使用 knex 在 postgres 数据库中创建一个简单的表:

function up(knex, Promise) {
return knex.schema.createTableIfNotExists('communities', (table) => {

    table.increments('id').primary().unsigned();

    table.string('name', 255).notNullable();
    table.string('slug', 100).notNullable();

    table.timestamp('createdAt').defaultTo( knex.fn.now() );
    table.timestamp('updatedAt');
});

};

function down(knex, Promise) {
  return knex.schema.dropTableIfExists(tableName);
};

module.exports = {
    tableName,
    up,
    down
}

我的问题是table.increments('id').primary() 创建了一个默认值具有nextval('communities_id_seq'::regclass) 的主键,并且我无法在没有id 的情况下进行插入(即使在原始sql 中)。

有谁知道如何让id默认递增?

【问题讨论】:

  • 你可能应该使用serial,而不是unsigned

标签: node.js postgresql knex.js


【解决方案1】:

在js中: table.increments()

输出sql: id int unsigned not null auto_increment primary key

check this out for more information

【讨论】:

    【解决方案2】:

    我的问题是 id 的值是一个空字符串,而不是 undefined 或 null,所以这打破了整数作为数据类型的约束。

    希望对你有帮助!

    【讨论】:

      【解决方案3】:

      聚会有点晚了,但我在同一个用例中遇到了这个问题。但是我的解决方案是我没有授予我的序列的所有正确权限,只有当我创建数据库时我的表。

      类似于"GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO PUBLIC"

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-28
        • 2018-11-23
        • 2019-08-07
        • 1970-01-01
        • 2015-05-11
        • 2012-12-08
        • 2012-03-13
        • 1970-01-01
        相关资源
        最近更新 更多