【发布时间】:2021-07-21 23:52:19
【问题描述】:
我有一个名为Stories 的表,其中有几列和 3 个外键:类别、子类别和语言。
为了进行关联,我添加了如下的 sequelize 函数,将 CategoryId、SubCategoryId 和 LanguageId 列添加到 Story 表中。
story.belongsTo(category, { as: 'Category' });
story.belongsTo(subCategory, { as: 'SubCategory' });
story.belongsTo(language, { as: 'Language' });
如何将故事添加到故事表? 下面是我的代码。
const Category = require('../models/category');
const SubCategory = require('../models/subCategory');
const Language = require('../models/language');
exports.postStory = (req, res, next) => {
const storyTitle = req.body.title;
const description = req.body.description;
const categoryId = req.body.categoryId;
const subCategoryId = req.body.subCategoryId;
const languageId = req.body.languageId;
Category.findOne({
where: {
id: categoryId
}
}).then(category => {
return SubCategory.findOne({
where: {
id: subCategoryId
}
})
}).then(subcategory => {
return Language.findOne({
where: {
id: languageId
}
}).then(language => {
//save operation here
const story = new Story({
story_type: storyType,
title: storyTitle,
description: description,
categoryId: categoryId,
subCategoryId: subCategoryId,
languageId: languageId,
createdBy: 1
});
return story.save()
.then((result) => {
res
.status(201)
.json({
message: "Story added to database",
statusCode: 201,
CreatedBy: 1,
result: result,
});
})
})
}).catch((error) => {
if (!error.statusCode) {
error.statusCode = 500;
}
next(error);
});
虽然它正在向 Story 表添加故事,但它没有添加 categoryId、Sub categoryId 和 languageId,它只是为这些字段添加空值,如下面的屏幕截图所示。
我不知道如何将 CategoryId、SubCategoryId、LanguageId 添加到故事中。
【问题讨论】:
标签: node.js express sequelize.js