我有 3 个模型用户、问题和视频
她是模型和创建功能外观的快照。
视频模型
'use strict';
module.exports = (sequelize, DataTypes) => {
var Video = sequelize.define('Video', {
transcription: {
type: DataTypes.TEXT
},
});
Video.associate = (models) => {
Video.belongsTo (models.Question,
{foreignKeyContraint : true , foreignKey: "questionId" });
}
Video.associate = (models) => {
Video.belongsTo(models.User, {
onDelete: "CASCADE",
foreignKey: 'userId'
});
}
return Video;};
问题模型:
module.exports = (sequelize, DataTypes) => {
var Question = sequelize.define('Question', {
text: {
type: DataTypes.TEXT,
allowNull: false,
}
});
Question.associate = (models) => {
Question.belongsTo(models.Script, {
onDelete: "CASCADE",
foreignKey: 'scriptId'
});
}
Question.associate = (models) => {
Question.hasMany(models.Questionvariation,
{
foreignKey: 'questionId',
as: 'questions',
});
}返回问题;};
用于创建函数
create(req, res) {
return Video
.create({
userId: req.body.user_id,
questionId: req.body.question_id,
transcription: req.body.transcription
})
.then(video =>
res.status(201).send(video))
.catch(error =>
res.status(400).send(error));
}
视频是创建的,但是它完全忽略了 questionId 的存在。
最佳答案
好的我已经解决了,问题是我必须在 Question 模型中添加一个 hasOne 关联
关于mysql - 1 :1 association 中未使用 sequelize 分配外键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45313996/