0
votes
  • I am using commands of sequelize to create and migrate Models to generate Tables in MySql database.
  • To generate new model: sequelize model:create --name Demo --attributes column:string
  • And After the Model and migration file generate, adding few lines of code to make association and foreign key constraints using given snippet of code:
  • In Derived/Child Table of Comapny:
      Employee.associate = function (models) {
            // associations can be defined here
            Employee.belongsTo(models.Company, {
                foreignKey: "companyId",
                onDelete: "CASCADE"
            })
        };
  • In Base/Parent table Comapany:

        Company.associate = function (models) {
            // associations can be defined here
            Company.hasMany(models.Employee,{
                foreignKey:"companyId",
            })
        };
    

But it does not reflect in Table->ALTER TABLE->ForeignKey Constraints.

2

2 Answers

0
votes

Your foreign keys are messed up.... i think it should look something more like below because you want a field called companyId to be in your employee table that references the id field of the company table

Employee.associate = function (models) {
            // associations can be defined here
            Employee.belongsTo(models.Company, {
                sourceKey: "companyId",
                foreignKey: "id",
                onDelete: "CASCADE"
            })
        };

and

Company.associate = function (models) {
        // associations can be defined here
        Company.hasMany(models.Employee,{
            foreignKey:"companyId",
        })
    };

this one will just assume your source key is your primary key which is probably id

0
votes
  • The foreign key constraint will reflect to the MySQL DB and its table, only when we change migration file too along with model file.
  • We have to add in migration file like:
    companyId:{
        type: Sequelize.INTEGER,
        onDelete: "CASCADE",
        references: {
            model: "Comapany",
            key: "id"
        }
      },
    
  • It worked successfully for me.