nnjeim / world

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

Issue with seeding countries when a foreign id is set #86

Closed fnagel closed 2 months ago

fnagel commented 2 months 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

 SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table referenced in a foreign key constraint (`laravel`.`accounts`, CONSTRAINT `accounts_country_foreign`) (Connection: mysql, SQL: truncate table `world_countries`)

Possible solution Same as for #15 but placed around here: https://github.com/nnjeim/world/blob/master/src/Actions/SeedAction.php#L144

Additional context Related to issue #15

nnjeim commented 2 months ago

@fnagel thank you for your input. Did you add a foreign key to the package migrations? if you are thinking of enhancing the package performance you need to take into count that all the data is dynamically cached.

let me know please if my understanding is correct here above. Or maybe you are creating an external model with a relation to the country.

nnjeim commented 2 months ago

closed by lack of activity

fnagel commented 2 months ago

@nnjeim Sorry for the late response. I was not able to get back to this project before.

Did you add a foreign key to the package migrations? if you are thinking of enhancing the package performance you need to take into count that all the data is dynamically cached. Or maybe you are creating an external model with a relation to the country.

Yes, but not for performance reasons but just to have a relation to another table. Maybe its more easy if I show you some code:

Schema::create('accounts', function (Blueprint $table) {
    $table->id();
    $table->timestamps();

    $table->string('country', 2);
});

and in another migration:

Schema::table('world_countries', function (Blueprint $table) {
    $table->index('iso2');
});
Schema::table('accounts', function (Blueprint $table) {
    $table->foreign('country')->references('iso2')->on('world_countries')
        ->onDelete('cascade')->onUpdate('cascade');
});

Please note that I'm a experienced Symfony and TYPO3 developer but a Laravel beginner, so I might have done something wrong here.

fnagel commented 1 month ago

@nnjeim Any feedback on this issue?

fnagel commented 3 weeks ago

@nnjeim Any feedback on this issue?