如何使用sequelize或sequelize-cli

时间:2016-09-23 02:55:03

标签: node.js join foreign-keys sequelize.js sequelize-cli

我正在为两种类型创建模型和迁移,Player和Team有多对多的关系。我正在使用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 个答案:

答案 0 :(得分: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');
  }
};