Sequelize, foreign keys as composite primary key

后端 未结 2 1345
陌清茗
陌清茗 2020-12-30 04:37

it is possible to define two foreign keys as a composite primary key of a model?

A user can only be a member of one family, a family can have many members and the fa

2条回答
  •  梦谈多话
    2020-12-30 04:48

    For anyone looking to create a composite index primary key based of the columns(keys) in your join table when doing migrations. You will need to add a primary key constraint for the two columns that you wish to act as the combined primary key for the table.

    module.exports = {
      up: function (queryInterface, Sequelize) {
        return queryInterface.createTable('itemtags', {
          itemId: {
            type: Sequelize.INTEGER,
            references: {
              model: 'items',
              key: 'id',
            },
            onDelete: 'CASCADE',
            onUpdate: 'CASCADE',
            allowNull: false
          },
          tagId: {
            type: Sequelize.INTEGER,
            references: {
              model: 'tags',
              key: 'id',
            },
            onDelete: 'CASCADE',
            onUpdate: 'CASCADE',
            allowNull: false
          }
        })
          .then(() => {
            return queryInterface.addConstraint('itemtags', ['itemId', 'tagId'], {
              type: 'primary key',
              name: 'gametag_pkey'
            });
          });
      },
      down: function (queryInterface, Sequelize) {
        return queryInterface.dropTable('gametags');
      }
    };
    

    Which is roughly the same as doing ALTER TABLE ONLY my_table ADD CONSTRAINT pk_my_table PRIMARY KEY(column1,column2); in postgres.

提交回复
热议问题