Skip to content
Advertisement

How to set extra attributes of through model on creation in SequelizeJS?

My models:

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

My associations:

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

My problem:

How can I create a Recipe with some Ingredients and the quantities attached to them?

I tried:

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

Records are created for Recipe, Ingredient and the Recipe_Ingredient. The only problem is that the value of the quantity is not collected from the data source.

Advertisement

Answer

It was not possible to do this in the past, but in October 23, 2018 this was fixed in sequelize PR #10050.

As of today (2018-10-24) the fix is not released yet, but as soon as v5.0.0-beta14 comes out, you’ll be able to do the following:

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

Also, note that the correct usage is recipe_ingredient: in the singular form, not in the plural form as you tried in your question. This makes sense, because for a given Ingredient, associated with a given Recipe, there is only one Recipe_Ingredient involved, always.

If you do not want to wait for v5.0.0-beta14 (although it will probably be released very soon), you can install it directly from github’s master branch as follows:

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

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement