首页 > 解决方案 > 如何在 SequelizeJS 中设置创建时通过模型的额外属性?

问题描述

我的模型:

 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]
})

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

标签: javascriptsequelize.js

解决方案


我找到了一个解决方案,灵感来自 pedro here 的答案(How do I ORM additional columns on a join table in sequelize?),并通过改变视角给出。

receipe (name:string)
ingredient (quantity:int)
type (name: string)

receipe.hasMany(ingredient, {as:'ingredients'} )
ingredient.belongsTo(type)

然后我可以使用这样的数据:

receipe.create({
  name: 'Pizza',
  ingredients:[
    {
      quantity: 5,
      type: {
         name: 'ingredient 1'
      }
    }, {
      quantity: 6,
      type: {
         name: 'ingredient 2'
      }
    } {
      quantity: 5,
      type_id: 1
    }]
}, {
    include:[{
       model; ingredient,
       as: 'ingredients',
       include:[{
         model: type
       }]
    }]
})

它有一些缺点,但对我来说已经足够了。

一个问题可能是,如果您添加两个相同新类型的项目,您将获得唯一键冲突(因为类型是唯一的,并且 sequelize 在尝试创建它之前不会尝试搜索该类型是否存在)。

另一个问题是,如果您只在数据中指定 type_id,它实际上不会返回结果中该类型所引用的类型。


推荐阅读