Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
      }
    ))
  },
like image 665
user3026715 Avatar asked Feb 26 '19 22:02

user3026715


People also ask

How do I add a foreign key in migration file Sequelize?

To create an attribute with a foreign key relationship, use the "references" and "referencesKey" fields: For example, the following would create a users table, and a user_emails table which references the users table. queryInterface. createTable('users', { id: { type: Sequelize.

How do I add a foreign key constraint in Sequelize?

Sequelize association methods also accept an options object that you can use to configure the details of the association. For example, you can change the foreign key name on the table by adding the foreignKey property: User. hasOne(Invoice, { foreignKey: "invoice_creator", // UserId -> invoice_creator });

How do I add a column to an existing table in Sequelize?

To add or delete columns in Sequelize CLI, we can use the sequelize migration:create command to create a migration file. Then we call addColumn to add a column and removeColumn to remove a column in the migration file. to create a migration file. in the migration file.

What is up and down in Sequelize migration?

If you mean what's up and what's down: - up: all commands will be executed when running sequelize db:migrate - down: all commands will be executed when running sequelize db:migrate:undo. Sequelize also says the development environment is default, but I experienced problems with this.


3 Answers

Shashikant Pandit's answer is good, but it is not cross-db compatible.

I ran into a problem using that migration because I have a PostgreSQL as the main DB, and an in-memory SQLite database for my tests. Running the migrations in the test environment (the tests start with a blank DB and run the migrations to get to current) produced an error in SQLite.

Here is a version that uses Sequelizes addConstraint built-in and should be cross-db compatible.

module.exports = {
  up: (queryInterface, Sequelize) => queryInterface
    .addConstraint('app_users', {
      type: 'UNIQUE',
      fields: ['email', 'column2', 'column3'],
      name: 'unique_user_email',
    }),
  down: (queryInterface, Sequelize) => queryInterface
    .removeConstraint('app_users', 'unique_user_email'),
};
like image 107
Nate Avatar answered Oct 19 '22 12:10

Nate


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!

like image 36
user3026715 Avatar answered Oct 19 '22 12:10

user3026715


For anyone looking for an answer on how to add foreign keys, use this Sequelize Constraints

like image 25
Jeffery ThaGintoki Avatar answered Oct 19 '22 11:10

Jeffery ThaGintoki