Getting around foreign key constraints when restoring a Craft CMS database

Are you getting foreign key constraint errors when trying to restore Craft CMS database backups? Here is how to solve it.

Every time I download a backup of a Craft 3 database and try to restore it to my local development environment, I get this error: Cannot add foreign key constraint

This happens because the SQL dump has the data in a different order than it should be loaded in according to the foreign key constraints.

The solution is to use a MySQL session variable to turn off foreign key constraints and be able to load your data in the order it is currently in.

How?

WARNING: Do NOT even think of doing this in your production environment. Only development. You’ve been warned.

Open your .sql dump in your favorite text editor and put this line at the top:

SET FOREIGN_KEY_CHECKS = 0;

Save it, then retry your import. Works for me every time.

I wrote this post so that I don’t have to search how to do it in six months when I need to do it again.

p.s. if you want to do something similar in postgres instead of mysql, search for SET CONSTRAINTS ALL DEFERRED.



Comments

Leave a Reply

Webmentions

If you've written a response on your own site, you can enter that post's URL to reply with a Webmention.

The only requirement for your mention to be recognized is a link to this post in your post's content. You can update or delete your post and then re-submit the URL in the form to update or remove your response from this page.

Learn more about Webmentions.