sql与同一表的三元关联

9jyewag0  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(292)

我想制作两个表,并设置它们之间的关联,使其具有如下外观:https://i.stack.imgur.com/hfjcp.png
我不太确定,但它看起来像是一个三元关联,其中两列来自同一个表。两者 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 } });
oprakyz7

oprakyz71#

我想你把具体联想的含义颠倒过来了:

// 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),并在battleparticipantids中使用它(battleid,participantid1,participantid2,other字段)。

相关问题