Sequelize not creating model association columns

我的梦境 提交于 2020-03-03 09:09:04

问题


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;
};


回答1:


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


来源:https://stackoverflow.com/questions/57351863/sequelize-not-creating-model-association-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!