Knex primary key auto increment

J.D. picture J.D. · Oct 2, 2016 · Viewed 13.4k times · Source

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

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).

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

Answer

Beknazar picture Beknazar · Feb 22, 2018

In js: table.increments()

Output sql: id int unsigned not null auto_increment primary key

check this out for more information