1

I don't see how i can update an junction table with multiple id's. So i want to update a junction table so that those rows with ids that are missing leave, and new ones are created.

This is my setup

  ActorFilm.belongsTo(models.Actor, { foreignKey: 'actorId', targetKey: 'id' });
  ActorFilm.belongsTo(models.Film, { foreignKey: 'filmId', targetKey: 'id' });

  Actor.belongsToMany(models.Film, { through: models.ActorFilm, foreignKey: 'actorId' });

  Film.belongsToMany(models.Actor, { through: models.ActorFilm, foreignKey: 'filmId' });

This is how i am add new Actor:

    const actor= await Actor.create({
        userId: userId,
        title: title,
        description: description
    });

    if (filmIds && filmIds.length) {
        await actor.setFilms(filmIds );
        const actorWithFilms = Actor.findByPk(actor.id, { include: Film });
        return actorWithFilms ;
    }
    
    return actor;

And i want to update Actorlike that:

   const editedActor = await Actor.update({
        title: title,
        description: description,
    }, {
        where: {
            id: actorId
        },
        returning: true,
    });

    return editedActor;

Where i need to put new ids array so that those that are missing leave, and new ones are created in junction table. Or should I first delete the unnecessary ones myself, check those that already exist and add new ones?

too29bad
  • 38
  • 1
  • 5
  • Isn't the call `await actor.setFilms(filmIds );` enough to delete old film links and add new ones? – Anatoly Jan 07 '22 at 20:30
  • @Anatoly Strange but initially it didn't work for me, now I decided to try it again and everything is working fine, thanks !!! – too29bad Jan 07 '22 at 21:23

1 Answers1

1

Just use

await actor.setFilms(filmIds );

it deletes old link records and added new ones.

Anatoly
  • 20,799
  • 3
  • 28
  • 42