Add documentation on foreign keys for creating key when there is existing data, will throw error unless nullable #48418
Unanswered
drewgallagher
asked this question in
Ideas
Replies: 1 comment 4 replies
-
Maybe, people don't want want the column to be nullable in general. Alternatively, you may want to do this: Schema::withoutForeignKeyConstraints(function () {
$table->unsignedBigInteger(self::COLUMN_NAME);
table->foreign(self::COLUMN_NAME)->references('id')->on('strategy_frequencies');
}); |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I just tried creating a foreign key for a table called
tasks
in a migration.Tasks should have a foreign key
strategy_frequency_id
that points toid
ontasks
Because
tasks
is an existing table with many records, when tried to create the foreign_key it threw the following errorThe cause was not clear, and I remembered after about 30 min of debugging that if there is data, and you try to apply a foreign key with existing records that don't have a tie to that foreign key, it will fail.
One workaround is to add
->nullable()
on the new foreign key column so that existing records don't cause an issue.This is done like so:
Once I did that, the migration passed.
Can we add documentation in laravel for this scenario here (for all versions of laravel supported)? https://laravel.com/docs/10.x/migrations#foreign-key-constraints
Otherwise it may be hard to figure this out again if I forget the solution and I'm sure other devs run into this issue periodically
Beta Was this translation helpful? Give feedback.
All reactions