简体   繁体   中英

Sequelize, how to update an associated model on another model

How do I update a model with new associations in Sequelize? The model is many-to-many with a join table. I tried this:

app.patch('/api/team/:id/newplayers', function(request, response){
  const players = request.body.players
  db.teams.findOne({
    where: {id: request.params.id},
    include: [{model: db.players}, {model: db.tournaments}]
  }).then(team => {
    return team.updateAttributes(players).then(updatedTeam => {
      response.json(updatedTeam)
    })
  })
})

But that doesn't work. It doesn't give any errors either. It just doesn't update "players".

Do I have to mess with the join table directly? I thought Sequelize would do a lot of that for you? My brain hurts :(

I think you have to delete all the old players and add new ones. Or more complex, you have to compare the old ones with the new ones. Insert which is not there/ edit which is already there.

The simplest way is delete all the old ones and add new ones. Something like.

.then(team => {
    return db.players.destroy({ 
        where: { id: team.players.map(player => player.id) }
    }).then(() => team)
}).then(team => {
    // should add team id to the players object
    return db.players.bulkCreate(players).then(updatedTeam => {
      response.json(updatedTeam)
    })
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM