sql - 与同一张表的三元关联
问题描述
我想创建 2 个表并在它们之间设置关联,使其看起来像这样:https ://i.stack.imgur.com/hFjCP.png
我不太确定,但它看起来像一个三元关联,其中 2 列来自同一个表。player1
和都是player2
类型User
。
我尝试过这样的事情,但我真的不确定这是要走的路。
const User = sequelize.define('User', { id: DataTypes.STRING })
const Battle = sequelize.define('Battle', { id: DataTypes.STRING })
const UserBattleParticipation = sequelize.define('UserBattleParticipation', {
battleId: {
type: DataTypes.STRING,
primaryKey: true,
allowNull: false,
references: {
model: Battle,
key: 'id'
}
},
player1: {
type: DataTypes.STRING,
primaryKey: true,
allowNull: false,
references: {
model: User,
key: 'id'
}
},
player2: {
type: DataTypes.STRING,
primaryKey: true,
allowNull: false,
references: {
model: User,
key: 'id'
}
},
additional: {
type: DataTypes.STRING,
allowNull: false
}
})
Battle.belongsToMany(User, { as: 'Participant', through:UserBattleParticipation, foreignKey: { name: 'battleId', allowNull: false} });
User.belongsToMany(Battle, { as: 'Attacker', through:UserBattleParticipation, foreignKey: { name: 'player1', allowNull: false } });
User.belongsToMany(Battle, { as: 'Target', through: UserBattleParticipation, foreignKey: { name: 'player2', allowNull: false } });
解决方案
- 我想您颠倒了具体关联的含义:
// If you want to get a list of attackers in a certain battle you should define such association:
// I recommend to use aliases in plural because it's many-to-`many`
Battle.belongsToMany(User, { as: 'Attackers', through:UserBattleParticipation, foreignKey: { name: 'battleId', allowNull: false }, otherKey: { name: 'player1', allowNull: false } });
// If you want to get a list of battle where a user was as an attacker you should define such association:
User.belongsToMany(Battle, { as: 'AttackerBattles', through:UserBattleParticipation, foreignKey: { name: 'player1', allowNull: false }, otherKey: { name: 'battleId', allowNull: false } });
- 您无法定义关联来获取战斗的所有参与者,因为您有两个不同的用户列。
如果您有一个预定义的参与某场战斗的用户列表,那么您可能应该更改您的结构并添加参与者(ParticipantId、BattleId、UserId)并在 BattleParticipants 中使用它(BattleId、ParticipantId1、ParticipantId2、其他字段)。
推荐阅读
- mongodb - 在 MongoDB 中将 java.net.URI 对象持久化为字符串
- javascript - 更新其他 React 组件
- json - 位置 0 的 JSON 内容中出现意外的令牌 < 错误
- javascript - 如何判断滚轮事件是否发生在带有滚动条的元素上?
- amp-html - Google AMP:呼叫跟踪动态号码
- java - 如何将字符串拆分为整个字符串?
- reactjs - next.js 中 _app.js 中的 Cookie 令牌访问
- python - Flask - 渲染页面而不返回
- azure-cosmosdb - 从多个模式中查询相同对象的 Cosmos DB
- python - 变异操作的 Dask 实现