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 ?
答案 0 :(得分:0)
我的问题的解决方案是在“关联对象”下的文档中(我必须跳过它)。
这解释了如果正确配置了belingsToMany,将动态创建几个方法来管理关联(getX,addX,getXs,addXs,...)。
我的第二个问题是我在belongsToMany中给出的别名,因为我不知道它取了模型的名称我自己设置了一个名称并交换了它们。
现在我删除了别名,它可以正常工作。
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'});
以下是我用来测试“添加关联”的代码。
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));