Sequelize.js foreign key

When using Sequelize.js, the following code doesn't add any foreign key on tables.

var MainDashboard = sequelize.define('main_dashboard', {
  title: Sequelize.STRING
}, {
  freezeTableName: true
})

MainClient.hasOne(MainDashboard, { foreignKey: 'idClient' })
MainDashboard.hasOne(MainClient, { foreignKey: 'clientId' })

sequelize.sync({ force: true })

Is there any way to force Sequelize.js to add these foreign key constraints?

Before I had the same problem, and solved when I understood the functioning of settings Sequelize.

Straight to the point!

Suppose we have two objects: Person and Father

var Person = sequelize.define('Person', {

        name: Sequelize.STRING
});

var Father = sequelize.define('Father', {

        age: Sequelize.STRING,
        //The magic start here
        personId{
              type: Sequelize.INTEGER,
              references: 'persons', // <<< Note, its table's name, not object name
              referencesKey: 'id' // <<< Note, its a column name
        }
});

Maybe it help you

Edit:

You can read this to understand better:

http://sequelizejs.com/blog/state-of-v1-7-0

You need to add foreignKeyConstraint:true
Try

MainClient.hasOne(MainDashboard, { foreignKey: 'idClient' , foreignKeyConstraint:true })

I just tried to run your code, and the rows seem to be created fine:

CREATE TABLE IF NOT EXISTS `main_dashboard` (`title` VARCHAR(255), `id` INTEGER NOT NULL auto_increment , `idClient` INTEGER, PRIMARY KEY (`id`)) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `main_client` (`id` INTEGER NOT NULL auto_increment,  `clientId` INTEGER, PRIMARY KEY (`id`)) ENGINE=InnoDB;

clientId is added to main_client, and idClient is added to main_dashboard

It seems you have slightly confused what the hasOne method does. Each time you call hasOne an association is created, so your code effectively associates the two tables twice. The method you are looking for is belongsTo

If you want each client to have one dashboard, the code would be the following:

MainClient.hasOne(MainDashboard, { foreignKey: 'clientId' })
MainDashboard.belongsTo(MainClient, { foreignKey: 'clientId' })

This creates a clientId field on the main_dashboard table, which relates to the id field of the main_client table

In short belongsTo adds the relation to the table that you are calling the method on, hasOne adds it on the table that is given as argument.