1

I have a User model (with associated migration file created by sequelize-cli):

'use strict';
module.exports = (sequelize, DataTypes) => {
    const User = sequelize.define('User', {
        dispName: DataTypes.STRING,
        email: DataTypes.STRING,
        phoneNum1: DataTypes.STRING
    }, {});
    User.associate = function (models) { // associations added manually
        User.belongsToMany(models.Role, { through: 'UserRoles', foreignKey: 'userId' });
    };
    return User;
};

here's the generated migration file:

'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Users', {
      cognitoId: { // modified: was an auto-incrementing integer
        allowNull: false,
        primaryKey: true,
        type: Sequelize.STRING(100)
      },
      dispName: {
        type: Sequelize.STRING(100) // modified: was just plain STRING
      },
      email: {
        type: Sequelize.STRING(100) // modified: was just plain STRING
      },
      phoneNum1: {
        type: Sequelize.STRING(15) // modified: was just plain STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Users');
  }
};

and a Role model (with associated migration file created by sequelize-cli):

'use strict';
module.exports = (sequelize, DataTypes) => {
    const Role = sequelize.define('Role', {
        name: DataTypes.STRING
    }, {});
    Role.associate = function (models) { // associations added manually
        Role.belongsToMany(models.User, { through: 'UserRoles', foreignKey: 'roleId' });
    };
    return Role;
};

here's the generated migration file for Role:

'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Roles', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      name: {
        type: Sequelize.STRING(100), // modified: was just plain STRING
        unique: true // Added manually
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Roles');
  }
};

When I run sequelize-cli db:migrate, the table UserRoles is not created. Why is that?

The Associations page of the Sequelize manual seems to suggest that defining the associations in the model file is all that is required...

Research:

markvgti
  • 4,321
  • 7
  • 40
  • 62

0 Answers0