首页 文章

如何使用sequelize或sequelize-cli创建带外键的连接表

提问于
浏览
13

我正在创建具有多对多关系的两种类型的玩家和团队的模型和迁移 . 我正在使用sequelize model:create,但是看不到如何指定外键或连接表 .

sequelize model:create --name Player --attributes "name:string"
sequelize model:create --name Team --attributes "name:string"

创建模型后,我添加关联 . 在播放器中:

Player.belongsToMany(models.Team, { through: 'PlayerTeam', foreignKey: 'playerId', otherKey: 'teamId' });

在团队中:

Team.belongsToMany(models.Player, { through: 'PlayerTeam', foreignKey: 'teamId', otherKey: 'playerId' });

然后运行迁移

sequelize db:migrate

有Player和Team的表,但数据库中没有连接表(也没有外键) . 如何创建外键和连接表?有没有关于如何做到这一点的权威指南?

1 回答

  • 10

    我也有像你这样的问题,我搜索过,但没有运气 . 这就是我所做的,我修改了你的代码 . 我手动为连接表创建迁移 . 我为两个外键添加复合索引 .

    module.exports = {
      up: function(queryInterface, Sequelize) {
        return queryInterface.createTable('PlayerTeam', {
          id: {
            allowNull: false,
            autoIncrement: true,
            primaryKey: true,
            type: Sequelize.INTEGER
          },
        playerId: {
          type: Sequelize.INTEGER,
          allowNull: false,
          references: {
            model: 'Player',
            key: 'id'
          },
          onUpdate: 'cascade',
          onDelete: 'cascade'
        },
        teamId: {
          type: Sequelize.INTEGER,
          allowNull: false,
          references: {
            model: 'Team',
            key: 'id'
          },
          onUpdate: 'cascade',
          onDelete: 'cascade'
        },
          createdAt: {
            allowNull: false,
            type: Sequelize.DATE
          },
          updatedAt: {
            allowNull: false,
            type: Sequelize.DATE
          }
        }).then(() => {
          // Create Unique CompoundIndex
          let sql = `CREATE UNIQUE INDEX "PlayerTeamCompoundIndex"
                  ON public."PlayerTeam"
                  USING btree
                  ("playerId", "teamId");
                `;
          return queryInterface.sequelize.query(sql, {raw: true});
          });
      },
      down: function(queryInterface, Sequelize) {
        return queryInterface.dropTable('PlayerTeam');
      }
    };
    

相关问题