在我的数据库中,我已经有了表,即:通知表、状态表,它们有多对多的关系,这就是为什么我有一个称为通知状态的透视表。我用迁徙创造了它们,用播种机播种,一切都很好。现在我意识到我需要一个与通知表有多对一关系的额外表(natification->has many->alertfrequency)。当我试图迁移它时,它确实允许我这样做。
这是我的通知表
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateNotificationsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('notifications', function (Blueprint $table) {
$table->increments('id');
$table->string('website_url');
$table->string('email');
$table->string('slack_channel');
$table->string('check_frequency');
$table->string('alert_frequency');
$table->string('speed_frequency');
$table->boolean('active');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('notifications');
}
}
警报频率表,我要添加的新表,
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAlertFrequenciesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('alertFrequencies', function (Blueprint $table) {
$table->increments('id');
$table->integer('notification_id');
$table->foreign('notification_id')
->references('id')->on('notifications')
->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('alertFrequencies');
}
}
当我试图添加时,我得到了以下约束
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `alertFrequencies` add constraint `alertfrequencies_notification_id_foreign` foreign key (`notification_
id`) references `notifications` (`id`) on delete cascade)
任何有想法或建议的人。我很感激所有的想法和建议。
最佳答案
首先要做的是添加unsigned()
,因为id
也是无符号的:
$table->integer('notification_id')->unsigned();
如果没有帮助,请分割密钥创建并添加外键约束:
Schema::create('alertFrequencies', function (Blueprint $table) {
$table->increments('id');
$table->integer('notification_id')->unsigned();
$table->timestamps();
});
Schema::table('alertFrequencies', function (Blueprint $table) {
$table->foreign('notification_id')->references('id')->on('notifications')->onDelete('cascade');
});
关于php - laravel:具有外键的播种机,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41632979/