Home > Software design >  Update a field of an associate table using the magic method of Sequelize/Node js
Update a field of an associate table using the magic method of Sequelize/Node js

Time:03-22

I have i table called Orders and another table called Cupons, this tables has a association many to one, Ordes has many cupons, and cupons belongs to order, i need to update the status of my cupom when i associate the cupons to a order, i tried this way but doesn't work

await item.addCupons(cupom.id, { // the item is the order created 
            through: {
                afiliado_id: afiliadoId, // and update the afiliado id 
                status: 'validado' // update de status of cupon to 'validado'
            }
        })
    ````

CodePudding user response:

You can only create a parent and child records using one method but not to update both. You need to explicitly call update for Order item:

await Cupon.update({
  afiliado_id: afiliadoId,
  status: 'validado'
}, {
 where: {
   id: cupom.id
 }
})
await item.addCupons(cupom.id)

through option is applicable for many-to-many relationships only.

  • Related