我已经用laravel编写了迁移,但当我运行此迁移时,我收到了以下错误
> 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)
我的迁移代码
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');
});
首先确保数据库中已经有一个campaign
表(查看迁移的时间戳(,以便在当前迁移中引用该表。基本上,要使此迁移工作,您需要在数据库中有一个活动表,在此之后不能运行campaign
表迁移。
另外,将campaign_id
更改为无符号整数
$table->unsignedInteger('campaign_id');
$table->foreign('campaign_id')->references('id')->on('campaigns')->onDelete('cascade');
您的迁移代码看起来像:
Schema::create('campaign_notifications', function (Blueprint $table) {
$table->increments('id');
$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->bigInteger('campaign_id')->unsigned();
$table->foreign('campaign_id')->references('id')->on('campaigns')->onDelete('cascade');
$table->index('campaign_id');
$table->timestamps();
});