Sequelize 不创建模型关联列 [英] 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 中创建一个外键,指向表 questions
This will create a foreign key in table question_categories, pointing to the table questions
question_categories.question_id -> questions.id
这篇关于Sequelize 不创建模型关联列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!