Search code examples
node.jsforeign-keyssequelize.jsdatabase-migration

Sequelize Migrations: Adding a foreign key constraint to a column on same table


So I'm trying to create a table with foreign key constraints to itself in migrations file.

I tried what I could following the sequelize docs and down below is the code I've tried, and I've also tried to move the foreign key references up to where the attributes were defined but it does not work there as well. Is there a way to do what I want to do here?

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('comments', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      root_id: {
        defaultValue: null,
        type: Sequelize.INTEGER
      },
      parent_id: {
        defaultValue: null,
        type: Sequelize.INTEGER
      },
    }).then(() => queryInterface.addConstraint(
      'comments',
      ['root_id'],
      {
        type: 'foreign key',
        name: 'root_id_fk',
        references: {
          table: 'comments',
          field: 'root_id'
        },
        onDelete: 'cascade',
        onUpdate: 'cascade'
      }
    )).then(() => queryInterface.addConstraint(
      'comments',
      ['parent_id'],
      {
        type: 'foreign key',
        name: 'parent_id_fk',
        references: {
          table: 'comments',
          field: 'parent_id'
        },
        onDelete: 'cascade',
        onUpdate: 'cascade'
      }
    ))
  },

Solution

  • I figured out what I was doing wrong, I was trying to create a foreign key to reference itself on the same table when I was supposed to be referencing a different column. Woops!