简体   繁体   中英

Update Field in Many to Many relation with Sequelize on NodeJs, with javascript

i have a relation Many to Many to do relation between Tournaments and Payers. So i have 3 models :

  • Player : with player_id
  • Tournament: with tournament_id
  • Participant (relation's table) witch join player_id, tournament_id, and contain un other field 'Status' to define if the player's participation to a tournament is 'accepted' or 'refused'.

My question is : how to do to update this field 'status' ?

I tried this, but is wrong !!!

const participation = await Participant.findAll({
        where: {
          user_id: userId,
          tournament_id: tournamentId,
        },
      });

await participation.update({ state: 'accepted' });

I am not sure this is the reason. But I assume that you shouldn't use the findAll method for your purpose.

findAll returns instance array, but update method belongs the model instance.

There are some possible solutions, I guess.

  1. Using Participant.findOne method and update it.

const participation = await Participant.findOne({ where: { user_id: userId, tournament_id: tournamentId });

  1. Using Participant.findAll method and loop the result array for update.

participation.map((p) => p.update({ state: 'accepted' });

  1. Using update method with where condition directly.

await Participant.update({ state: 'accepted' }, { where: { user_id: userId, tournament_id: tournamentId };

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