0

I'm having an issue with Sequelize because I don't know how to approach the problem.

I have 3 tables : A (game), B(platform) and AB (game_platform). A can have 1 to many B and B can have 0 to many A. To do that I made an association table : AB.

In Sequelize I created the A,B,AB models then I did :

db.Game.belongsToMany(db.Platform, {as: 'Game', through: 'GamePlatformsJoin', foreignKey: 'game_platforms_fk_game'});
db.Platform.belongsToMany(db.Game, {as: 'Platform', through: 'GamePlatformsJoin', foreignKey: 'game_platforms_fk_platform'});

Now this is how it will go : On my website platforms will be created and then games. When a game is created the user will need to define the platform(s) associated to it. But how can I tell Sequelize that I want a new entry in my association table ? I can add it as with any other table but is there a simpler way ?

rXp
  • 617
  • 2
  • 12
  • 25

1 Answers1

2

The solution to my problem was in the documentation under Associating Objects]1 (I must have skipped it).

This explains that if belingsToMany is correctly configured several methods will be dynamically created to mange the association (getX, addX, getXs, addXs,...).

My second issue was the alias I gave in belongsToMany, since I didn't know it took the name of the model I set a name myself and swapped them.

Now that I removed the aliases it works fine.

db.Game.belongsToMany(db.Platform, {through: db.GamePlatforms, foreignKey: 'game_platforms_fk_game'});
db.Platform.belongsToMany(db.Game, {through: db.GamePlatforms, foreignKey: 'game_platforms_fk_platform'});

And here is the code I use to test "add an association".

Game.find({where: {game_short: 'SFV'}})
              .then(function(game) {
                Platform.find({where: {platform_short: 'PC'}})
                  .then(plat => game.addPlatform(plat));
              })
              .catch(err => console.log('Error asso game and platform', err));
rXp
  • 617
  • 2
  • 12
  • 25