Sequelize.js foreign key


Question

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?

1
30
3/18/2015 2:38:35 PM

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
        }
});

Person.hasMany(Father); // Set one to many relationship

Maybe it help you

Edit:

You can read this to understand better:

http://docs.sequelizejs.com/manual/tutorial/associations.html#foreign-keys

30
1/16/2019 3:34:02 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon