问题描述
我在使用 Sequelize 时遇到问题,因为我不知道如何解决这个问题.
I'm having an issue with Sequelize because I don't know how to approach the problem.
我有 3 张桌子:A(游戏)、B(平台)和 AB(游戏平台).A 可以有 1 到多个 B,B 可以有 0 到多个 A.为此,我制作了一个关联表:AB.
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.
在 Sequelize 中,我创建了 A、B、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'});
现在是这样的:在我的网站上将创建平台,然后创建游戏.创建游戏时,用户需要定义与之关联的平台.但是我如何告诉 Sequelize 我想在关联表中添加一个新条目?我可以像添加任何其他表格一样添加它,但有没有更简单的方法?
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 ?
推荐答案
我的问题的解决方案在 Associating Objects 下的文档中]1(我肯定跳过了).
The solution to my problem was in the documentation under Associating Objects]1 (I must have skipped it).
这说明如果belingsToMany 配置正确,将动态创建几个方法来管理关联(getX、addX、getXs、addXs...).
This explains that if belingsToMany is correctly configured several methods will be dynamically created to mange the association (getX, addX, getXs, addXs,...).
我的第二个问题是我在 belongsToMany 中给出的别名,因为我不知道它取了我自己设置的名称并交换了模型的名称.
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));
这篇关于Sequelize如何使用关联表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!