Knex 主键自增
Knex primary key auto increment
我正在使用 knex 在 postgres 数据库中创建一个简单的 table:
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默认增加?
我的问题是 id 的值是一个空字符串,而不是未定义或 null,因此这打破了整数作为数据类型的约束。
希望对您有所帮助!
在 js 中:
table.increments()
输出sql:
id int unsigned not null auto_increment primary key
晚会有点晚了,但我遇到了相同用例的问题。然而,我的解决方案是,我没有为我的序列授予所有正确的权限,只有在我创建数据库时为我的表授予权限。
所以类似于 "GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO PUBLIC"
我正在使用 knex 在 postgres 数据库中创建一个简单的 table:
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默认增加?
我的问题是 id 的值是一个空字符串,而不是未定义或 null,因此这打破了整数作为数据类型的约束。
希望对您有所帮助!
在 js 中:
table.increments()
输出sql:
id int unsigned not null auto_increment primary key
晚会有点晚了,但我遇到了相同用例的问题。然而,我的解决方案是,我没有为我的序列授予所有正确的权限,只有在我创建数据库时为我的表授予权限。
所以类似于 "GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO PUBLIC"