0
votes

I have a database that was created with Postgres that was set up for a single foreign key association, Now, this would be mapped as a role table model consider I have two tables user and roles roles contain role details and user contain user details of role

   const uuid = require('uuid/v4');
            ('use strict');
            module.exports = (sequelize, DataTypes) => {
              const role = sequelize.define(
                'role',
                {
                  id: {
                    allowNull: false,
                    primaryKey: true,
                    type: DataTypes.UUID,
                  },

                  name: {
                    type: DataTypes.STRING,
                    allowNull: false,
                  },
                },
                {}
              );
              role.beforeCreate((role) => (role.id = uuid()));
              role.associate = function (models) {
                role.hasMany(models.user), { foreignKey: 'roleId', as: 'user_roleId' };
              };
              return role;
            };

    role migration 

    'use strict';
    module.exports = {
      up: (queryInterface, Sequelize) => {
        return queryInterface.createTable('roles', {
          id: {
            allowNull: false,
            primaryKey: true,
            type: Sequelize.UUID,
          },
          name: {
            type: Sequelize.STRING,
          },
          createdAt: {
            allowNull: false,
            type: Sequelize.DATE,
          },
          updatedAt: {
            allowNull: false,
            type: Sequelize.DATE,
          },
        });
      },
      down: (queryInterface, Sequelize) => {
        return queryInterface.dropTable('roles');
      },
    };

    user model

    const uuid = require('uuid/v4');
    ('use strict');
    module.exports = (sequelize, DataTypes) => {
      const user = sequelize.define(
        'user',
        {
          id: {
            allowNull: false,
            primaryKey: true,
            type: DataTypes.UUID,
          },

          firstName: {
            type: DataTypes.STRING,
            allowNull: false,
          },
          lastName: DataTypes.STRING,
          email: {
            type: DataTypes.STRING,
            allowNull: false,
          },
          password: {
            type: DataTypes.STRING,
            allowNull: false,
          },

          phoneNumber: {
            type: DataTypes.STRING,
          },
          roleId: {
            type: DataTypes.UUID,
          },
        },
        {
          timestamps: true,
          paranoid: true,
          defaultScope: {
            attributes: { exclude: ['password'] },
          },
        }
      );
      user.beforeCreate((user) => (user.id = uuid()));
      user.associate = function (models) {
        user.belongsTo(models.role, { foreignKey: 'roleId', onDelete: 'CASCADE' });
      };
      return user;
    };

    user migration
    'use strict';
    module.exports = {
      up: (queryInterface, Sequelize) => {
        return queryInterface.createTable('users', {
          id: {
            allowNull: false,
            primaryKey: true,
            type: Sequelize.UUID,
          },
          firstName: {
            type: Sequelize.STRING,
          },
          lastName: {
            type: Sequelize.STRING,
          },
          email: {
            type: Sequelize.STRING,
          },
          password: {
            type: Sequelize.STRING,
          },
          phoneNumber: {
            type: Sequelize.STRING,
          },
          roleId: {
            type: Sequelize.UUID,
          },

          createdAt: {
            allowNull: false,
            type: Sequelize.DATE,
          },
          updatedAt: {
            allowNull: false,
            type: Sequelize.DATE,
          },
          deletedAt: {
            allowNull: true,
            type: Sequelize.DATE,
          },
        });
      },
      down: (queryInterface, Sequelize) => {
        return queryInterface.dropTable('users');
      },
    };

after running the migration these tables are created in my database.role_id is also present in the user table. but role_id is not generated as a foreign key in my user table. also please verify that the relationship which is mention here(one to many) is correct or not.

please verify my code and give me any suggestions if any changes required. I'm new in development

1

1 Answers

0
votes

Your user migration also needs to know about the foreign key; you do this by adding a references: key to the column definition. The Sequelize documentation has a foreign key example; scroll about half way down the page (or just search for references).

In your case the user migration should look something like:

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('users', {
      // ... other fields omitted
      roleId: {
        type: Sequelize.UUID,
        references: {
          model: { tableName: 'role' }
          key: 'id',
        },
      },
      // ... more fields omitted
    });
  },
  // down: omitted
}