Batman
Batman

Reputation: 6353

Sequelize not creating model association columns

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

Upvotes: 1

Views: 1334

Answers (1)

Aditya
Aditya

Reputation: 2246

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

Upvotes: 0

Related Questions