首页 > 解决方案 > 与同一张表的三元关联

问题描述

我想创建 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 } });

标签: sqlsequelize.js

解决方案


  1. 我想您颠倒了具体关联的含义:
// 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 }  });
  1. 您无法定义关联来获取战斗的所有参与者,因为您有两个不同的用户列。

如果您有一个预定义的参与某场战斗的用户列表,那么您可能应该更改您的结构并添加参与者(ParticipantId、BattleId、UserId)并在 BattleParticipants 中使用它(BattleId、ParticipantId1、ParticipantId2、其他字段)。


推荐阅读