如何使用sequelize在express js中为一条记录添加多个外键

How to add multiple foreign keys for one record in express js using sequelize

我有一个名为 Stories 的 table,其中只有几列和 3 个外键:类别、子类别和语言。

为了建立关联,我添加了如下的 sequelize 函数,它向 Story table 添加了 CategoryIdSubCategoryIdLanguageId 列。

story.belongsTo(category, { as: 'Category' });
story.belongsTo(subCategory, { as: 'SubCategory' });
story.belongsTo(language, { as: 'Language' });

如何将故事添加到故事 table? 下面是我的代码。

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 table 添加故事,但它没有添加 categoryId、Sub categoryId 和 languageId,它只为这些字段添加空值,如下面的屏幕截图所示。

我不知道如何将 CategoryId、SubCategoryId、LanguageId 添加到故事中。

您在创建故事实例时使用的外键在 camelCase 中,但您在 PascalCase 中定义了别名。

更改关联定义中的任一别名

story.belongsTo(category, { as: 'category' });
story.belongsTo(subCategory, { as: 'subCategory' });
story.belongsTo(language, { as: 'language' });

或在故事实例中更改密钥

const story = new Story({
  story_type: storyType,
  title: storyTitle,
  description: description,
  Category: categoryId,
  SubCategoryId: subCategoryId,
  LanguageId: languageId,
  createdBy: 1
});

注意: 为所有关联添加外键约束以不允许 insert/update 空值。

story.belongsTo(category, {
  as: "category",
  foreignKey: {
    allowNull: false
  }
});