【发布时间】:2017-09-11 05:52:06
【问题描述】:
我正在尝试使用联结表创建一个实例和多个具有多对多关系的相关实例。
在创建多个相关实例时,我还需要向联结表上的属性添加一个值。我不知道是否是我缺乏对续集或承诺的了解导致了我的问题。
我使用的代码如下。此代码确实将项目添加到数据库中,但我需要在操作完成后重定向,这不起作用。
基本上,我需要创建一个食谱。一旦创建,我需要创建成分并将它们与该食谱相关联。成分存储在来自 HTML 页面上的表单的数组中。在关联成分时,我需要将成分数量添加到 RecipeIngredients 表中,这是关系的直通部分(联结表)。
global.db.Recipe.belongsToMany(
global.db.Ingredient,
{
as: 'Ingredients',
through: global.db.RecipeIngredients,
foreignKey: 'recipe_id'
});
global.db.Ingredient.belongsToMany(
global.db.Recipe,
{
as: 'Recipes',
through: global.db.RecipeIngredients,
foreignKey: 'ingredient_id'
});
router.post('/new', ensureLoggedIn, bodyParser.json(), function (req, res) {
var recipeName = req.body.recipe_name;
var steps = req.body.steps;
var ingredients = req.body.ingredients;
var ingredientQty = {};
var currentIngredient;
var ingredientsToAdd = [];
db.Recipe.create({
recipe_name: recipeName,
directions: steps,
FamilyId: req.user.FamilyId,
CreatedBy: req.user._id
})
.then(function (recipe) {
for (var i = 0; i < ingredients.length; i++) {
currentIngredient = ingredients[i];
ingredientQty[currentIngredient.ingredient_name] =
currentIngredient.quantity;
db.Ingredient.findOrCreate({
where: {
ingredient_name: currentIngredient.ingredient_name,
FamilyId: req.user.FamilyId
}
})
.spread(function (ingredient, created) {
if (created) {
console.log("Added Ingredient to DB: " +
currentIngredient.ingredient_name);
}
ingredient.Recipes = {
ingredient_quantity:
ingredientQty[ingredient.ingredient_name]
};
ingredient.CreatedBy = req.user._id;
recipe.addIngredient(ingredient)
.then(function () {
console.log("Added Ingredient " + ingredient.ingredient_name
+ " to Recipe " + recipe.recipe_name);
});
})
}
})
.finally(function(recipe){
res.redirect('/recipes');
});
});
任何帮助将不胜感激。我知道我因为尝试在循环中使用 Promise 而遇到问题,我只是不知道我还能如何做到这一点。
【问题讨论】:
标签: node.js postgresql express sequelize.js