当Sequelize创建关联字段时,我有些困惑。
我已经使用sequelize-cli创建了迁移。这生成了一个迁移和模型文件。然后在模型文件中填充关联。然后运行npx sequelize-cli db:migrate
。
这将创建表,但不会创建模型中定义的关联所需的外键。
例如: 迁移问题:
"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;
};
答案 0 :(得分:0)
您需要提供外键中使用的列。 这些线上的东西
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中创建一个外键,指向表问题
question_categories.question_id -> questions.id