nnjeim / world

A Laravel package which provides a list of the countries, states, cities, currencies, timezones and languages.
MIT License
761 stars 104 forks source link

On db:seed truncate problem with foreignId on models #15

Closed dgironella closed 2 years ago

dgironella commented 2 years ago

Describe the bug If you create a model and have a foreignId in a for example countries id, when try to db:seed and error about truncate happend.

To Reproduce Create a model with a foreignId $table->foreignId('country_id')->references('id')->on('countries');

php artisan db:seed --class=WorldSeeder

Error

Syntax error or access violation: 1701 Cannot truncate a table referenced in a foreign key constraint (fer.taxes, CONSTRAINT taxes_country_id_foreign FOREIGN KEY (country_id) REFERENCES fer.countries (id)) (SQL: truncate table countries)

Possible solution

Schema::disableForeignKeyConstraints(); <- before truncate Schema::enableForeignKeyConstraints(); <- after truncate

nnjeim commented 2 years ago

@dgironella i am not sure if i got it right, i would suggest that you drop all the tables and seed again. Truncating the table would not work because of the foreign ids.

Mello21century commented 2 years ago

His answer is optimal in SeedAction

            app($this->modules[$module]['class'])->truncate();

Should be changed to

            Schema::disableForeignKeyConstraints();
            app($this->modules[$module]['class'])->truncate();
            Schema::enableForeignKeyConstraints();

Please apply it as an update The problem occurs on db:seed while the migration running complete all tables are empty but there is another table have a foreign id from your package. While your package doesn't execute delete command and it execute truncate. I managed to add it to WorldSeeder before all the seeding process but it's needed only before the truncate command

Best regards

nnjeim commented 2 years ago

@dgironella @Mello21century Thank you your input. please consider upgrading to v1.1.13 where the proposed modification was implemented.