如何用外键创build带有sequelize或sequelize-cli的连接表

我正在为两种types创build模型和迁移,玩家和团队有许多关系。 我使用sequelize模型:创build,但不看如何指定外键或连接表。

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

模型创build后,我添加关联。 玩家:

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

团队:

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

然后迁移与运行

 sequelize db:migrate 

有玩家和团队的表,但数据库中没有连接表(也不是外键)。 如何创build外键和连接表? 有没有关于如何做到这一点的权威指南?

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

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