Working with Sequelize and MySQL database, I was trying to achieve composite primary keys combination in junction table, but unfortunately without result.
I have tables:
They are in relation many to many. In junction table user_has_project I want two primary keys combination: user_id and project_id.
Sequelize models definition:
User:
module.exports = function(sequelize, Sequelize) {
var User = sequelize.define('user', {
id: {
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER(11)
},
name: {
type: Sequelize.STRING(100),
allowNull: false
}
},{
timestamps: false,
freezeTableName: true,
underscored: true
});
User.associate = function (models) {
models.user.belongsToMany(models.project, {
through: 'user_has_project',
foreignKey: 'user_id',
primaryKey: true
});
};
return User;
}
Project:
module.exports = function(sequelize, Sequelize) {
var Project = sequelize.define('project', {
id: {
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER(11)
},
name: {
type: Sequelize.STRING(100),
allowNull: false
}
},{
timestamps: false,
freezeTableName: true,
underscored: true
});
Project.associate = function (models) {
models.project.belongsToMany(models.user, {
through: 'user_has_project',
foreignKey: 'project_id',
primaryKey: true
});
};
return Project;
}
I was trying to 'force' Primary keys definition in user_has_project table using "primaryKey: true" in both models association, but definition above is creating only user_id as PRI and project_id as MUL