On db:seed truncate problem with foreignId on models
dgironella opened this issue · comments
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
@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.
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
@dgironella @Mello21century Thank you your input. please consider upgrading to v1.1.13 where the proposed modification was implemented.