编写一个菜谱应用程序,并与mysql一起使用sequelize。
有两个相关的表:recipes表和foreignkey为recipeid的recipeamounts表。
一个食谱可以有一个或多个基于用户输入的成分。添加配方时,必须填充recipes和recipeamounts表。
我已经用promises创建了下面的函数,但是我不明白如何在recipeamounts中正确填充recipeid foreignkey。它必须与recipes表中新添加的配方的id相同。
exports.addRecipe = function (req, res) {
var promises = [];
promises.push(
db.Recipe.create({
RecipeName: req.body.RecipeName,
RecipeDescription: req.body.RecipeDescription
})
)
for (var i = 0; i < req.body.RecipeIngredients.length; i++) {
promises.push(
db.RecipeAmount.create({
Amount: req.body.RecipeIngredients[i].AmountForSmall,
Size: 'sm',
Type: 'smoothie',
// IngredientId: 10,
// RecipeId: 1
})
);
promises.push(
db.RecipeAmount.create({
Amount: req.body.RecipeIngredients[i].AmountForMedium,
Size: 'md',
Type: 'smoothie',
// IngredientId: 10,
// RecipeId: 1
})
);
promises.push(
db.RecipeAmount.create({
Amount: req.body.RecipeIngredients[i].AmountForLarge,
Size: 'lg',
Type: 'smoothie',
// IngredientId: 10,
// RecipeId: 1
})
);
}
sequelize.Promise.all(promises).then(function() {
console.log("all the files were created");
});
};
为了测试的目的,我尝试硬编码recipeid,但是当我这样做时,我得到了以下错误:
Unhandled rejection SequelizeForeignKeyConstraintError: Cannot add or update a child row: a foreign key constraint fails
1条答案
按热度按时间nsc4cvqm1#
用这个工作: