Sequelize migrations - add foreign key constraint issue
Asked Answered
R

2

6

I need to remove the existing foreign key constraint on a column and add a new constraint with same name which refers to primary key of another table.

I am getting an error ERROR: Constraint type must be specified through options.type. Though I am providing constraint type in option's object as third parameter.

Below is the migration code for reference.

 async up(queryInterface, Sequelize){
    const transaction = await queryInterface.sequelize.transaction();
    try {
      await queryInterface.removeConstraint(
        'shipments',
        'shipments_status_id_fkey',
        { transaction }
      );
      await queryInterface.addConstraint(
        'shipments',
        'status_id',
        {
          type: 'foreign key',
          name: 'shipments_status_id_fkey',
          references: {
            table: 'statuses',
            field: 'id'
          },
          transaction
        }
      );
      await transaction.commit();
    } catch (err) {
      await transaction.rollback();
      throw err;
    }
  }
Reedy answered 2/7, 2020 at 14:52 Comment(0)
G
8

Documentation here shows that options should be the second parameter to addConstraint function. https://sequelize.org/master/class/lib/dialects/abstract/query-interface.js~QueryInterface.html#instance-method-addConstraint

await queryInterface.addConstraint(
        'shipments',
        {
          type: 'foreign key',
          fields: ['status_id']
          name: 'shipments_status_id_fkey',
          references: {
            table: 'statuses',
            field: 'id'
          },
          transaction
        }
      );
Grasping answered 2/7, 2020 at 15:16 Comment(1)
I am using sequelize v5 and followed this document. sequelize.org/v5/class/lib/…Reedy
H
0

If you're using version 6 of Sequelize you need to define the fields/columns as well inside references. See the example below.

await queryInterface.addConstraint(TableName, {
      fields: ["FIELD_NAME_OF_THE_FOREIGN_KEY"],
      type: "foreign key",
      name: "YOUR_FOREIGN_KEY_NAME",
      references: {
        table: "REFERENCE_TABLE",
        fields: ["PRIMARY_KEY_OF_THE_REFERENCE_TABLE"],
        key: "PRIMARY_KEY_OF_THE_REFERENCE_TABLE",
      },
    });

After adding the Constraint in the child table/s, Run sequelize db:migrate and it worked!. Hope it helps.

Herbert answered 21/10, 2022 at 12:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.