1

I have this already created two tables called User and Profile.

This is how my model for User looks like..

const Sequelize = require("sequelize");
const db = require("../db");

const User = db.define("User", {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true,
  },
  name: {
    type: Sequelize.STRING,
    allowNull: true,
  },
  email: {
    type: Sequelize.STRING,
    allowNull: false,
    unique: true,
   validator: {
      isEmail: true,
    },
  },
});

module.exports = User;

and model for Profile looks like..

const Sequelize = require("sequelize");
const User = require("./User");

const db = require("../db");

const Profile = db.define("Profile", {
  image: {
    type: Sequelize.STRING,
  },

  description: {
    type: Sequelize.TEXT,
  },

});


module.exports = Profile;

Now I want to define a one-to-one relationship between User and Profile such that user will recieve a profileId column. so i am defining it like this

Profile.hasOne(User, {
  foreignKey: {
    allowNull: false,
  },
});
User.belongsTo(Profile);

Now i am not able to figure out how to write migrations for the newly added foreign key can anyone help me please.. Thanks.

1 Answers1

0

I got the answer. for someone who is confused like me here is the answer

since the User table already exists, migrations for the foreignkey will look like this

module.exports = {
  async up(queryInterface, Sequelize) {
    return await queryInterface.addColumn("Users", "ProfileId", {
      type: Sequelize.INTEGER,
      references: {
        model: "Profiles",
        key: "id",
      },
    });
  },

  async down(queryInterface, Sequelize) {
    return await queryInterface.removeColumn("Users", "ProfileId", {
      type: Sequelize.INTEGER,
      references: {
        model: "Profiles",
        key: "id",
      },
    });
  },
};

the Users in addColumn and removeColumn is the name of the table in which foreignkey was added.

the ProfileId is the name for foreignkey which you would have specified in hasOne.

hope this helps..