I am trying to create a user > friend relationship in sequelize. Therefore, I created a user model and a belongsToMany relationship through a join-table called friends. It created the table but the foreignKeys userId and friendId are not created. I would be happy if someone could help me out.
User model:
var User = sequelize.define('user', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true
},
emailaddress: {
type: Sequelize.STRING
},
firstname: {
type: Sequelize.STRING
},
lastname: {
type: Sequelize.STRING
},
description: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
}
}, {
freezeTableName: true,
classMethods: {
associate: function (models) {
User.belongsToMany(models.user, {
as: "user",
through: "friend"
});
User.belongsToMany(models.user, {
as: "friend",
through: "friend"
});
User.sync({
force: true
})
}
}
});
friend model
var Friend = sequelize.define('friend', {
// userId: DataTypes.INTEGER,
// friendId: DataTypes.INTEGER,
status: {
type: DataTypes.BOOLEAN,
defaultValue: 0
}
}, {
freezeTableName: true,
classMethods: {
associate: function (models) {
Friend.sync()
}
}
});
This generates the following field in the friend table:
id status createdAt updatedAt
I would like the following fields:
id status userId friendId createdAt updatedAt
package.json > "sequelize": "^3.17.1",
After some debugging I found out that the problem was that I called Table.sync on initializing every table instead of doing it just once when all tables are defined (see the example code in the sequelize express example on github: https://github.com/sequelize/express-example). This corrupted the table creation process.