排序如何使用关联表? [英] Sequelize how to use association table?

查看:74
本文介绍了排序如何使用关联表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Sequelize上遇到问题,因为我不知道如何解决该问题。

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

我有3张桌子:A(游戏),B(平台)和AB(game_platform)。
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 ?

推荐答案

我的问题的解决方案位于关联对象下的文档中。 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));

这篇关于排序如何使用关联表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆