How to choose name of Foreign Key column using Sequelize and mySql?

I managed to fix the problem:

Instead of only using the "foreignKey"-option in the belongsTo-statement, it should also be used in the "hasMany"-statement.

The two models that were posted in the original question remained the same. The only thing I had to change was the location of the foreignKey option:

var db = require('../models/index');
db["Company"].hasMany(db["Department"], {as: 'departments'});
db["Department"].belongsTo(db["Company"], {foreignKey: 'companyId', foreignKeyConstraint: true});

changed to:

var db = require('../models/index');
db["Company"].hasMany(db["Department"], { foreignKey: 'companyId'});
db["Department"].belongsTo(db["Company"], {foreignKey: 'companyId'});

In the version 4.4.0, there is a targetKey option for the belongsTo function.

const User = this.sequelize.define('user', {/* attributes */})
const Company  = this.sequelize.define('company', {/* attributes */});

User.belongsTo(Company, {foreignKey: 'fk_companyname', targetKey: 'name'}); // Adds fk_companyname to User

more information on http://docs.sequelizejs.com/manual/tutorial/associations.html#target-keys


I know this thread is somewhat old, but I stumbled upon it when having problems declaring a 1:n association. I am using sequelize 5.21.5. The way to reference keys in the attributes changed from (borrowed from your example):

companyId: {
  type:           DataTypes.INTEGER,
  references:     'Companies',
  referencesKey:  'companyId'
}

to:

companyId: {
  type: DataTypes.INTEGER,
  references: {
    model: 'Company',
    key: 'companyId'
  }
}

Hope this helps any weary traveler along the way!