Monday 10 April 2017

How to enforce foreign key constraints using KnexJS?

Created a sqlite3 schema using KnexJS and everything went fine. There's an issue though. I have two tables , one called "todo" which has a foreign key "userID" that references the "id" field in "users" and the other table obviously is "users".The issue is that If i add a new entry to the "todo" table and leave the "userID" field empty , i dont get any error!!! i.e i can have the "userID" field empty which mean the constraints dose not work. any idea WTH am i doing wrong? thanks in advancehere's the code// Todo migration exports.up = function(knex, Promise) { return knex.schema.createTable('todo', function(table){ table.increments(); table.text('title').notNullable(); table.integer('priority').notNullable(); table.text('description'); table.boolean('done').notNullable().defaultTo(false); table.timestamps(); table.integer('userID').unsigned(); table.foreign('userID').references('id').inTable('users').onDelete('CASCADE').onUpdate('CASCADE'); }); }exports.down = function(knex, Promise) { return knex.schema.dropTable('todo'); }// Users migrationexports.up = function(knex, Promise) { return knex.schema.createTable('users', function(table){ table.increments(); table.string('name').notNullable().unique(); }); };exports.down = function(knex, Promise) { return knex.schema.dropTable('users'); };

Submitted April 10, 2017 at 12:09PM by munzman

No comments:

Post a Comment