Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knex primary key auto increment

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?

like image 597
J.D. Avatar asked Oct 02 '16 08:10

J.D.


2 Answers

In js: table.increments()

Output sql: id int unsigned not null auto_increment primary key

check this out for more information

like image 77
Beknazar Avatar answered Oct 18 '22 05:10

Beknazar


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.

Hope it helps!

like image 44
J.D. Avatar answered Oct 18 '22 04:10

J.D.