Sequelize how to use association table?

萝らか妹 提交于 2020-04-12 05:00:59

问题


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 ?


回答1:


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));


来源:https://stackoverflow.com/questions/43997395/sequelize-how-to-use-association-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!