postgresql Knex主键自增

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39815188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:24:16  来源:igfitidea点击:

Knex primary key auto increment

node.jspostgresqlknex.js

提问by J.D.

I'm using knex to create a simple table in postgres database:

我正在使用 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
}

My problem is that table.increments('id').primary()creates a primary key that for default value has nextval('communities_id_seq'::regclass)and I can't do an insert without an id (even in raw sql).

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

Does anyone know how to make the id increment by default?

有谁知道默认情况下如何使 id 递增?

采纳答案by J.D.

My problem was that the value for id was an empty string and not undefined or null, so that was braking the constraint for integer as data type.

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

Hope it helps!

希望能帮助到你!

回答by Beknazar

In js: table.increments()

在js中: table.increments()

Output sql: id int unsigned not null auto_increment primary key

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

check this out for more information

看看这个以获取更多信息

回答by Lachlan Young

A bit late to the party but I was having this issue with the same use case. However my solution was I didnt have all the correct permissions granted to my sequences, only my tables when i ceated the DB.

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

So something along the lines of "GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO PUBLIC"

所以类似的东西 "GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO PUBLIC"