1

I'm a little confused with when Sequelize creates the fields for associations.

I've created my migrations using sequelize-cli. This generated a migration and model file. Then in the model file I populated my associations. Then ran npx sequelize-cli db:migrate.

This creates the tables but not the foreign keys needed for the associations defined in the model.

For example: migration-quesions:

"use strict";
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable("questions", {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      category: {
        type: Sequelize.INTEGER
      },
      question: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        defaultValue: new Date(),
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        defaultValue: new Date(),
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable("questions");
  }
};

model-questions:

"use strict";
module.exports = (sequelize, DataTypes) => {
  const questions = sequelize.define(
    "questions",
    {
      question: DataTypes.STRING,
      weight: DateTypes.INTEGER
    },
    {}
  );
  questions.associate = function(models) {
    // associations can be defined here
    models.questions.hasOne(models.question_categories);
    models.questions.hasMany(models.question_answers);
  };
  return questions;
};

enter image description here

Batman
  • 5,563
  • 18
  • 79
  • 155
  • Based on your associations, the `categories` table should have a `question_id` FK and the `answers` table should have a `question_id` FK too. So you want the migration operation to create `question_id` FK on `categories` and `answers` tables? Do I understand correctly? – Lin Du Feb 11 '20 at 12:36

1 Answers1

0

You need to provide the columns which are used in the foreign key. Something on these lines

  questions.associate = function(models) {
    // associations can be defined here
    models.questions.hasOne(models.question_categories, { foreignKey: 'question_id' });
    models.questions.hasMany(models.question_answers, { foreignKey: 'question_id' });
  };

This will create a foreign key in table question_categories, pointing to the table questions

question_categories.question_id -> questions.id
Aditya
  • 2,148
  • 3
  • 21
  • 34