Sequelizejs将关系表中的字段获取到关联盟友ToyToMany

时间:2018-11-29 18:22:28

标签: node.js postgresql sequelize.js

我在具有以下架构的Postgre数据库的NodeJs上使用Sequelizejs@4.37.6

players架构

id
first_name
last_name
...
status

sports架构

id
name
...
status

player_sports架构

id
player_id
sport_id
rating
trophies

我的协会是

Player.belongsToMany(Sport, {through: 'player_sports', foreignKey: 'player_id'});
PlayerSport.hasOne(Player, {foreignKey: 'id'});
PlayerSport.hasOne(Sport, {foreignKey: 'id'});

我正在查询所有具有以下运动的球员

Player.findAll({
    include: ['sports']
});

一切工作都按预期进行,但我也希望在关系中包含ratingtrophies字段,请提出一种在播放器或player.sports中获得这些字段的方法

预先感谢

1 个答案:

答案 0 :(得分:1)

您可以像这样从rating获得trophiesplayer

player.sports.player_sports.trophies

player.sports.player_sports.rating

如果遇到错误,请尝试将PlayerSport的关联更改为此:

PlayerSport.belongsTo(Player, {foreignKey: 'player_id'});
PlayerSport.belongsTo(Sport, {foreignKey: 'sport_id'});