Knex主键自动增量

J.D*_*.D. 8 postgresql node.js knex.js

我正在使用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');
});
Run Code Online (Sandbox Code Playgroud)

};

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

module.exports = {
    tableName,
    up,
    down
}
Run Code Online (Sandbox Code Playgroud)

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

有没有人知道如何默认增加id?

小智 5

在js中: table.increments()

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

看看这个以获取更多信息


J.D*_*.D. 2

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

希望能帮助到你!