Search code examples
javascriptnode.jsexpresssequelize.jssequelize-cli

Sequelize many-to-many updating junction table


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?


Solution

  • Just use

    await actor.setFilms(filmIds );
    

    it deletes old link records and added new ones.