Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Mysterious Errors – SequelizeBaseError: Insert or Update on Table Violates Foreign Key Constraints

Sequelize is a great library, but its documentation leaves a lot to be desired.

Recently, while writing unit tests for an e-commerce site project, I came across this cryptic error:

SequelizeBaseError: insert or update on table "reviews" violates foreign key constraint "reviews_user_id_fkey"

From the error, it's not too clear what has gone wrong.

The model I was testing had two associations, using Sequelize's belongsTo method.

Sequelize generates setter methods with the name of the associated model. For example, the association Review.belongsTo(User) will generate a method setUser().

Our Review would now have an integer id of the associated model.

I assumed that I could fake associations by calling review.setUser() with an integer directly, even though no model in the database had that id. Nope!

Here's the problematic test:

It turns out that to call the setAssociation method, you'll need to create actual records in your database.

How I fixed it:

Now the test will work. You'll have actual data to call your setAssociation method on.

@TheBrotherFromASouthernMother

This comment has been minimized.

Copy link

TheBrotherFromASouthernMother commented Nov 13, 2018

This really helped me out, thanks for writing this!

@joscelyn

This comment has been minimized.

Copy link

joscelyn commented Apr 7, 2019

Thanks a lot !

@bihire

This comment has been minimized.

Copy link

bihire commented Apr 26, 2019

Big love to comment this

@fortunee

This comment has been minimized.

Copy link

fortunee commented Jul 17, 2019

This is good. Thanks

@frandroid

This comment has been minimized.

Copy link

frandroid commented Jan 14, 2020

🙏🏻🙏🏻🙏🏻

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.