Catfish
Catfish

Reputation: 19294

Sequelize not creating foreign keys on db as expected

I have this

Given this ERD, I'm trying to figure out why foreign keys are not being created on documentChildren and documentAttribute as they each have a column which should be a FK to document.

My sequelize models are all working fine, but i'm curious what i'm doing wrong in that real FK's are not being generated.

document migration:

'use strict'
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('documents', {
      id: {
        allowNull: false,
        primaryKey: true,
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4
      },
      ...
    })
  }
  ...
}

documentChildren migration:

'use strict'
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('documentChildren', {
      id: {
        allowNull: false,
        primaryKey: true,
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4
      },
      documentId: {
        allowNull: false,
        type: Sequelize.UUID,
        references: {
          model: 'documents',
          key: 'id'
        }
      },
      ...
    })
  }
  ...
}

documentAttribute migration:

'use strict'
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('documentAttributes', {
      id: {
        allowNull: false,
        primaryKey: true,
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4
      },
      documentId: {
        allowNull: false,
        type: Sequelize.UUID,
        references: {
          model: 'documents',
          key: 'id'
        }
      },
      ...
    })
  }
  ...
}

document model associations:

document.associate = function (models) {
    document.hasMany(models.documentAttribute)
    document.hasMany(models.documentChildren)
  }

enter image description here

Upvotes: 0

Views: 123

Answers (1)

Gonzalo.-
Gonzalo.-

Reputation: 12672

Your code shows

"documentId" uuid NOT NULL REFERENCES documents(id)

The REFERENCES documents(id) is the FK. Check postgresql-docs

You are confused with the indexes creation, that does not mean having a FK.

Upvotes: 1

Related Questions