Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[fix][php]: Disable Foreign Key Checks during truncating before running database seeding #626

Open
idehen-divine opened this issue Feb 28, 2025 · 3 comments

Comments

@idehen-divine
Copy link

idehen-divine commented Feb 28, 2025

SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table referenced in a foreign key constraint (hng_boilerplate.category_product, CONSTRAINT category_product_category_id_foreign) (Connection: mysql, SQL: truncate table categories)

This error occurs because the categories table is referenced by the category_product table through a foreign key constraint. MySQL prevents truncating tables when they have foreign key constraints.

the solutions is to Disable Foreign Key Checks when seeding

@idehen-divine idehen-divine changed the title [FIX][php]:ArticlesTableSeeder issue on php artisan db:seed [fix][php]: Disable Foreign Key Checks during truncating before running database seeding Feb 28, 2025
@bhimbho
Copy link
Contributor

bhimbho commented Feb 28, 2025

The solution isn't removing FK checks, its ensuring the category needed is first created in the categories table before creating them in category_product

@idehen-divine
Copy link
Author

@bhimbho here we are truncating the tables before seeding, now it's not only the category_product that has the issue all tables that ref a foreign id has it

Image

this was my solution

@idehen-divine
Copy link
Author

and this is done directly on database seeder solving all the recurring issues on all seeders

try recreating the error with

php artisan migrate:fresh --seed

idehen-divine added a commit to idehen-divine/hng_boilerplate_php_laravel_web that referenced this issue Mar 2, 2025
Modified DatabaseSeeder.php to temporarily disable
foreign key checksbefore truncating tables, ensuring
smooth database seeding without constraint violations.

Fixes hngprojects#626
idehen-divine added a commit to idehen-divine/hng_boilerplate_php_laravel_web that referenced this issue Mar 2, 2025
Modified DatabaseSeeder.php to temporarily disable
foreign key checksbefore truncating tables, ensuring
smooth database seeding without constraint violations.

Fixes hngprojects#626
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants