通过 Sequelize 联接表嵌套关联数据



使用Sequelize,我试图获得这样的输出:

[{
"Id": 1,
"Name": "Game 1",
"Teams": [{
"Id": 1,
"Name": "Team 1",
"Users": [{
"Id": 1,
"UserName": "User 1"
}]
}]
}, {
"Id": 2,
"Name": "Game 2",
"Teams": [{
"Id": 1,
"Name": "Team 1",
"Users": [{
"Id": 2,
"UserName": "User 2"
}]
}]
}]

请注意,Team 1 有 2 个不同的用户,但这只是因为他们每个游戏都是这样设置的......因此,用户不会直接绑定到团队,而是通过团队游戏约束绑定。 基本上,我的游戏有很多团队,我的游戏/团队有很多用户......多对多关系。 我试图遵循这个线程,但似乎他们在那里做的事情实际上不起作用,因为我尝试这样做:

// models/Game.js
module.exports = (sequelize, types) => {
const GameModel = sequelize.define('Game', {
Id: {
type: types.INTEGER,
primaryKey: true,
autoIncrement: true
},
Name: {
type: types.STRING,
allowNull: false
}
});
GameModel.associate = (models) => {
GameModel.belongsToMany(models.Team, {
as: 'Teams',
foreignKey: 'GameId',
through: models.GameTeam
});
};
return GameModel;
};
// models/Team.js
module.exports = (sequelize, types) => {
const TeamModel = sequelize.define('Team', {
Id: {
type: types.INTEGER,
primaryKey: true,
autoIncrement: true
},
Name: {
type: types.STRING,
allowNull: false
}
});
TeamModel.associate = (models) => {
TeamModel.belongsToMany(models.Game, {
as: 'Games',
foreignKey: 'TeamId',
through: models.GameTeam
});
};
return TeamModel;
};
// models/User.js
module.exports = (sequelize, types) => {
const UserModel = sequelize.define('User', {
Id: {
type: types.INTEGER,
primaryKey: true,
autoIncrement: true
},
UserName: {
type: types.STRING,
allowNull: false
}
});
return UserModel;
};
// models/GameTeam.js
module.exports = (sequelize, types) => {
const GameTeamModel = sequelize.define('GameTeam', {
Id: {
type: types.INTEGER,
primaryKey: true,
autoIncrement: true
}
});
GameTeamModel.associate = (models) => {
GameTeamModel.belongsToMany(models.User, {
as: 'Users',
through: 'GameTeamUser'
});
};
return GameTeamModel;
};

上面的模型可以很好地创建表,其中包含似乎是适当的列。 然后,我进行一些插入,并尝试在游戏模型上使用findAll,如下所示:

GameModel.findAll({
include: [{
association: GameModel.associations.Teams,
include: [{
association: GameTeamModel.associations.Users,
through: {
attributes: []
}
}],
through: {
attributes: []
}
}]
});

查询在第二个包含处开始出错,与用户的关联。 因为我试图将用户嵌套在团队中,所以我认为联接会尝试使用直通表 (GameTeams.Id( 上的唯一 ID,但查询最终会使用以下内容:

LEFT OUTER JOIN `GameTeamUser` AS `Teams->Users->GameTeamUser` ON `Teams`.`Id` = `Teams->Users->GameTeamUser`.`GameTeamId`

我以为 ON 会GameTeams.Id = Teams->Users->GameTeamuser.GameTeamId,但我不知道为什么不是,以及如何调整它......我尝试在我的包含中使用自定义on(根据文档(,但它似乎被完全忽略了。 有人有什么建议吗? 或者可能是构建它的更好方法,所以它按照我想要的方式工作?

我认为你把这种想法过于复杂化了,你有多对多。我可以看到您的 GameTeam 模型的字段与您在其他模型中声明的外键不匹配......

您的数据库表是什么样的?

我说得对吗,一个游戏有很多团队,一个团队有很多用户......但是,用户一次只能在一个团队中,而一个团队一次只能在一个游戏中?(我假设游戏/团队加入和团队/用户加入只是连接表中的临时记录,在游戏结束后消失等(

最新更新