首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用sequelize或sequelize-cli创建带有外键的连接表

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

Stack Overflow用户
提问于 2016-09-23 10:55:03
回答 1查看 5.4K关注 0票数 15

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

代码语言:javascript
运行
复制
sequelize model:create --name Player --attributes "name:string"
sequelize model:create --name Team --attributes "name:string"

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

代码语言:javascript
运行
复制
Player.belongsToMany(models.Team, { through: 'PlayerTeam', foreignKey: 'playerId', otherKey: 'teamId' });

在团队中:

代码语言:javascript
运行
复制
Team.belongsToMany(models.Player, { through: 'PlayerTeam', foreignKey: 'teamId', otherKey: 'playerId' });

然后,使用运行迁移

代码语言:javascript
运行
复制
sequelize db:migrate

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-24 00:30:00

我也和你一样有同样的问题,我已经搜索过了,但没有找到。这就是我所做的,我按照你的代码修改了。我手动为join表创建迁移。并且我为两个外键都添加了复合索引。

代码语言:javascript
运行
复制
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');
  }
};
票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39651853

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档