我有一个“帖子”表和一个“到达”表,其中引用了“ flightno” (以文本字符串格式)作为外键。但是,当我运行Laravel迁移时,出现了可怕的错误:
[Illuminate \ Database \ QueryException] SQLSTATE [HY000]:常规错误:1005无法创建表
atc
。#sql-2350_84
(错误号:150“外键约束是 格式不正确”)(SQL:alter tablearrival
添加约束arrival_flightno_foreign
外键(flightno
)引用了posts
(flightno
)[PDOException] SQLSTATE [HY000]:常规错误:1005无法创建表
atc
。#sql-2350_84
(错误号: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();
});
答案 0 :(得分:0)
在我看来,您忘记了放置索引和设置flightno
列的长度。这应该起作用:
帖子
Schema::create('posts', function (Blueprint $table) {
// ...
$table->string('flightno', 30)->index();
// ...
});
到达
Schema::create('arrival', function (Blueprint $table) {
// ...
$table->string('flightno', 30)->index();
// ...
});
答案 1 :(得分:0)
在外键列中使用 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();
});
它将解决很多面临这个问题的人的问题。