我的模特:

 Recipe (id, name)
 Ingredient (id, name)
 Recipe_Ingredient (recipeId, ingredientId, quantity)


我的关联:

Recipe.belongsToMany(Ingredient, { through: Recipe_Ingredient })
Ingredient.belongsToMany(Recipe, { through: Recipe_Ingredient })


我的问题:

如何创建包含某些成分及其数量的食谱?

我试过了:

Recipe.create({
  name: 'Pizza',
  ingredients:[
    {
      name: 'mozarella',
      recipe_ingredients: {
          quantity: 5
      }
    }
  ]
}, {
    include:[Ingredient]
})


将为配方,成分和配方成分创建记录。唯一的问题是未从数据源收集数量值。

最佳答案

过去无法执行此操作,但是在2018年10月23日,此问题已在续篇PR #10050中修复。

截至今天(2018-10-24),该修补程序尚未发布,但是v5.0.0-beta14出现后,您将能够执行以下操作:

Recipe.create({
    name: 'Pizza',
    ingredients: [
        {
            name: 'mozarella',
            recipe_ingredient: {
                quantity: 5
            }
        }
    ]
}, {
    include: Ingredient
})


另外,请注意正确的用法是recipe_ingredient:的单数形式,而不是您在问题中尝试的复数形式。这是有道理的,因为对于与给定配方相关联的给定成分,始终仅涉及一个Recipe_Ingredient。

如果您不想等待v5.0.0-beta14(尽管它可能很快就会发布),则可以直接从github的master分支中进行安装,如下所示:

npm install --save https://github.com/sequelize/sequelize/tarball/master

07-24 18:43
查看更多