When attempting to run a migration in Laravel, I encountered the following error message:
> SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
> (SQL: alter table `campaign_notifications` add constraint `campaign
> _notifications_campaign_id_foreign` foreign key (`campaign_id`) references `campaigns` (`id`) on delete cascade)
Below is the migration code I've written:
Schema::create('campaign_notifications', function (Blueprint $table) {
$table->increments('id');
$table->integer('campaign_id')->index();
$table->string('user_uuid')->nullable();
$table->string('post_id')->default(0);
$table->tinyInteger('is_opened')->default(0);
$table->tinyInteger('sent')->default(0);
$table->string('payload')->nullable();
$table->string('failed_type')->nullable();
$table->timestamps();
$table->foreign('campaign_id')->references('id')->on('campaigns')->onDelete('cascade');
});
The error seems to be related to the foreign key constraint on the campaign_id column, which references the id column in the campaigns table with cascading delete behavior. However, I'm unsure why this error is occurring. Can anyone provide insights into what might be causing this issue and how to resolve it? Any help would be appreciated. Thank you!
campaigntable is all ready migratedcampaign_notifications.campaign_idfield is of same type ascampaigns.id. If incampaignstable you use$table->increments('id');it isunsignedBigIntegerfield type that would need to be added in child table structure.