Laravel 迁移错误号:150“外键约束格式不正确”
Posted
技术标签:
【中文标题】Laravel 迁移错误号:150“外键约束格式不正确”【英文标题】:Laravel migration Error no: 150 "Foreign key constraint is incorrectly formed" 【发布时间】:2019-07-10 10:54:18 【问题描述】:我有一个“posts”表和一个“arrival”表,其中引用了“flightno”(以文本字符串格式)作为外键。但是,当我运行 Laravel 迁移时,我得到了可怕的错误:
[照亮\数据库\查询异常] SQLSTATE[HY000]: 一般错误: 1005 Can't create table
atc
.#sql-2350_84
(errno: 150 "外键约束是 格式不正确”) (SQL: alter tablearrival
add constraintarrival_flightno_foreign
外键 (flightno
) 引用posts
(flightno
))[PDO异常] SQLSTATE[HY000]: 一般错误: 1005 Can't create table
atc
.#sql-2350_84
(errno: 150 "外键约束是 格式不正确")
帖子
Schema::create('posts', function (Blueprint $table)
$table->increments('id');
$table->string('flightno');
$table->string('flighttype');
$table->string('toa');
$table->string('doa');
$table->string('runway');
$table->string('route');
$table->string('parking');
$table->timestamps();
);
到达
Schema::create('arrival', function (Blueprint $table)
$table->increments('id');
$table->string('flightno');
$table->string('cleaning');
$table->string('rampservice');
$table->string('waste');
$table->string('deicing');
$table->foreign('flightno')->references('flightno')->on('posts')->onDelete('cascade');
$table->timestamps();
);
【问题讨论】:
【参考方案1】:在外键列中使用 unsignedBigInteger 以避免外键数据类型不匹配的问题。
例如,在您的到达表中,使用 flightno 的类型为 unsignedBigInteger。
帖子:
Schema::create('posts', function (Blueprint $table)
$table->increments('id');
$table->string('flightno');
$table->string('flighttype');
$table->string('toa');
$table->string('doa');
$table->string('runway');
$table->string('route');
$table->string('parking');
$table->timestamps();
);
到达:
Schema::create('arrival', function (Blueprint $table)
$table->increments('id');
//---Change flightno type to unsignedBigInteger and if u faced any problem just use nullable at the end of flightno.
$table->unsignedBigInteger('flightno');
$table->string('cleaning');
$table->string('rampservice');
$table->string('waste');
$table->string('deicing');
$table->foreign('flightno')->references('flightno')->on('posts')->onDelete('cascade');
$table->timestamps();
);
它将解决很多人面临这个问题的问题。
【讨论】:
【参考方案2】:在我看来,您忘记放置索引并设置 flightno
列的长度。这应该有效:
帖子
Schema::create('posts', function (Blueprint $table)
// ...
$table->string('flightno', 30)->index();
// ...
);
到达
Schema::create('arrival', function (Blueprint $table)
// ...
$table->string('flightno', 30)->index();
// ...
);
【讨论】:
以上是关于Laravel 迁移错误号:150“外键约束格式不正确”的主要内容,如果未能解决你的问题,请参考以下文章
laravel 5.4 迁移错误:150“外键约束格式不正确”
Laravel 迁移:“外键约束格式不正确”(errno 150)
Laravel 迁移:Errcode:150“外键约束格式不正确”