续集不创建模型关联列 [英] Sequelize not creating model association columns
问题描述
当Sequelize创建关联字段时,我有些困惑.
I'm a little confused with when Sequelize creates the fields for associations.
我已经使用sequelize-cli创建了迁移.这生成了一个迁移和模型文件.然后在模型文件中填充关联.然后运行npx sequelize-cli db:migrate
.
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.
例如: 迁移问题:
"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");
}
};
模型问题:
"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;
};
推荐答案
您需要提供外键中使用的列. 这些线上的东西
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' });
};
这将在表question_categories中创建一个外键,指向表问题
This will create a foreign key in table question_categories, pointing to the table questions
question_categories.question_id -> questions.id
这篇关于续集不创建模型关联列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!