2016-09-23 130 views
9

我正在为两种类型创建模型和迁移,即具有多对多关系的Player和Team。我使用sequelize模型:create,但没有看到如何指定外键或连接表。如何使用外键创建连接表,并使用sequelize或sequelize-cli

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 

运行有对球员和团队表,但没有连接表(也不外键)在数据库中。如何创建外键和连接表?有没有关于如何做到这一点的权威指南?

回答

9

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

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'); 
    } 
};