Zack Carlson
Zack Carlson

Reputation: 89

SequelizeForeignKeyConstraintError: insert or update on table ... violates foreign key constraint \..._id_fkey\"

I don't understand this error (SequelizeForeignKeyConstraintError: insert or update on table \"segment\" violates foreign key constraint \"segment_id_fkey\"). I've read other answers on this topic on StackOverflow, but nothing that has pointed me in the right direction.

What I'm trying to do is have a user submit a form with some data that's then saved as a Segment model. The Segment model looks like so:

module.exports = (sequelize, DataTypes) => {
  const Segment = sequelize.define(
    'segment',
    {
      id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
      },
      provider_id: {
        type: DataTypes.INTEGER,
        references: {
          model: 'provider',
          key: 'id'
        }
      },
      summary_id: {
        type: DataTypes.INTEGER,
        references: {
          model: 'summary',
          key: 'id'
        }
      },
      audience_id: {
        type: DataTypes.INTEGER,
        references: {
          model: 'audience',
          key: 'id'
        }
      },
      onboarding_id: {
        type: DataTypes.INTEGER,
        references: {
          model: 'onboarding',
          key: 'id'
        }
      }
    },
    {
      // disable the modification of table names; By default, sequelize will automatically
      // transform all passed model names (first parameter of define) into plural.
      // if you don't want that, set the following
      freezeTableName: true,
      tableName: 'segment'
    }
  );

  Segment.associate = models => {
    Segment.belongsTo(models.Provider, { foreignKey: 'id' });
    Segment.belongsTo(models.Summary, { foreignKey: 'id' });
    Segment.belongsTo(models.Audience, { foreignKey: 'id' });
    Segment.belongsTo(models.Onboarding, { foreignKey: 'id' });
  };

  return Segment;
};

The models that the Segment refers to (ie Provider, Summary, Audience, Onboarding), have a hasMany relationship to the Segment model. Something like so:

Provider.associate = models => {
  Provider.hasMany(models.Segment, { foreignKey: 'provider_id' });
};

I have a feeling that the error has to do with the way I'm associating my models.

Any and all help is super appreciated! Thanks in advance!

Upvotes: 4

Views: 6792

Answers (1)

Dinesh Kumar
Dinesh Kumar

Reputation: 19

Keep associations like:

Segment.associate = models => {
    Segment.belongsTo(models.Provider, { foreignKey: 'provider_id' });
    Segment.belongsTo(models.Summary, { foreignKey: 'summary_id' });
    Segment.belongsTo(models.Audience, { foreignKey: 'audience_id' });
    Segment.belongsTo(models.Onboarding, { foreignKey: 'onboarding_id' });
}

and in Providers, summary, Audience and oboarding files:

Providers.associate = models => {
    Providers.belongsTo(models.Segments, { foreignKey: 'id' });    
};

Upvotes: 2

Related Questions