简体   繁体   中英

Sequelize assocation to same table

I have a table called documents that has a column called parentId which is a reference to another document record.

With my current code i'm getting the error

insert or update on table "documents" violates foreign key constraint "documents_parentId_fkey"

documents migration

'use strict'
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('documents', {
      id: {
        allowNull: false,
        primaryKey: true,
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4
      },
      parentId: {
        allowNull: true,
        type: Sequelize.UUID,
        references: {
          model: 'documents',
          key: 'id'
        }
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      lastUpdatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      lastUpdatedBy: {
        allowNull: false,
        type: Sequelize.UUID
      }
    })
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('documents')
  }
}

document model

'use strict'

module.exports = (sequelize, DataTypes) => {
  const document = sequelize.define('document', {
    id: {
      allowNull: false,
      primaryKey: true,
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4
    },
    parentId: {
      allowNull: true,
      type: DataTypes.UUID,
      references: {
        model: 'documents',
        key: 'id'
      }
    },
    lastUpdatedBy: {
      allowNull: false,
      type: DataTypes.UUID
    }
  },
  {
    updatedAt: 'lastUpdatedAt'
  })
  document.associate = function (models) {
    document.belongsTo(models.document, { foreignKey: 'parentId' })
  }
  return document
}

How do you properly do associations to the same table?

I have a self referencing table configured with the constraints: false setting.

MyModel.belongsTo(MyModel, {
  as: 'parentMyModel',
  foreignKey: 'parentId',
  constraints: false,
});

Looks like the constraint is valid (and a good one). My payload that I was submitting had a parent uuid which didn't actually reference any document with that id.

So my code was right, the data I was submitting was wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM