19

I tried the code in the link to create FK:

how to do knex.js migration

I got an error on line:

table.bigInteger('AddressId')
    .unsigned()
    .index()
    .inTable('Address')
    .references('id');

The error:

    TypeError: Object # has no method 'inTable' at 
     TableBuilder_MySQL._fn (/Users/lwang/knex/migrations/20150204161920_lei_maigration.js:15:56) at
     TableBuilder_MySQL.TableBuilder.toSQL (/Users/lwang/knex/node_modules/knex/lib/schema/tablebuilder.js:61:12) at 
     SchemaCompiler_MySQL.createTable (/Users/lwang/knex/node_modules/knex/lib/schema/compiler.js:14:53) at 
     SchemaCompiler_MySQL.SchemaCompiler.toSQL (/Users/lwang/knex/node_modules/knex/lib/schema/compiler.js:35:24) at 
     SchemaBuilder_MySQL.SchemaBuilder.toSQL (/Users/lwang/knex/node_modules/knex/lib/schema/builder.js:41:35) at 
     Runner_MySQL. (/Users/lwang/knex/node_modul...
Esteban Borai
  • 2,311
  • 1
  • 21
  • 27
Lei
  • 189
  • 1
  • 1
  • 4

2 Answers2

38

This might come a little late but the error is because:

table.bigInteger('AddressId')
    .unsigned()
    .index()
    .inTable('Address')
    .references('id');

Should be written:

table.bigInteger('AddressId')
    .unsigned()
    .index()
    .references('id')
    .inTable('Address');

The inTable function only exists after calling references as explained in the documentation http://knexjs.org/#Schema-inTable

Sets the "table" where the foreign key column is located after calling column.references.

Esteban Borai
  • 2,311
  • 1
  • 21
  • 27
devconcept
  • 3,665
  • 1
  • 26
  • 40
3

I think there has been a change on how to assign foreign keys.

Instead of doing this:

table.bigInteger('AddressId')
.unsigned()
.index()
.inTable('Address')
.references('id');

I did this:

table.integer('AddressId').unsigned()
tables.foreign('AddressId').references('Address.id');

and it worked well for me.

For further reference you can check this github gist: https://github.com/knex/knex/issues/245

Jobizil
  • 66
  • 1
  • 5