I am trying to associate User and Roles so I can give a user a role. I keep on getting an error when I try to add a user, without the association it will work, but I want to associate them.
here is my User model
'use strict';
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define("User", {
user_id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
username: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: false
},
password: {
type: DataTypes.STRING,
allowNull: false
},
first_name: {
type: DataTypes.STRING,
allowNull: false
},
last_name: {
type: DataTypes.STRING,
allowNull: false
},
img_src: DataTypes.STRING,
//updated_at: DataTypes.DATE,
status: {
type: DataTypes.INTEGER,
defaultValue: 1
},
//active: DataTypes.BOOLEAN
},
{
timestamps: true,
underscored: false,
freezeTableName: true,
tableName: 'user'
});
User.associate = (models) => {
User.belongsTo(models.Role, { foreignKey: 'role_id'})};
return User;
}
here is my Role model
module.exports = (sequelize, DataTypes) => {
const Role = sequelize.define('Role', {
role_id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
title: DataTypes.STRING,
description: DataTypes.STRING
},
{
timestamps: true,
underscored: false,
freezeTableName: true,
tableName: 'role',
initialAutoIncrement: 2000
});
Role.associate = (models) => {
Role.hasMany(models.User, { as: 'users', foreignKey: 'user_id' })};
return Role;
}
when I try to add a user, here is the error I get in my terminal
UnhandledPromiseRejectionWarning: SequelizeForeignKeyConstraintError: Cannot add or update a child row: a foreign key constraint fails (`e2e-react-db`.`user`, CONSTRAINT `user_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `role` (`role_id`) ON DELETE CASCADE ON UPDATE CASCADE)
I guess that the best way to do this is to add a new column on User model called role_id , and the association:
User.associate = (models) => { User.hasOne(models.Role, { foreignKey: 'role_id' })};
Remove all the Other associations. and I advise you to revert all migrations, make these changes that I said, and run the migrations again