我正在使用Laravel 5.6应用程序,其中我有2个表,主要是sponsors
表和children
表。在迁移表之间创建一对多关系。一个孩子可能有很多赞助商。
问题是使用php artisan migrate
命令迁移它们时出现此错误:
Illuminate \ Database \ QueryException:SQLSTATE [HY000]:常规错误: 1005无法创建表
larangular
。#sql-520c_21f
(错误号:150 “外键约束格式不正确”)(SQL:alter tablesponsors
添加约束sponsors_child_id_foreign
外键 (child_id
)在删除级联上引用了children
(id
)
赞助商迁移
public function up()
{
Schema::create('sponsors', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('child_id')->unsignedInteger();
$table->foreign('child_id')->references('id')->on('children')->onDelete('cascade');
$table->foreign('child_id')->references('id')->on('children');
$table->string('email')->unique();
$table->string('phone');
$table->string('nationality');
$table->timestamps();
});
}
儿童迁移
public function up()
{
Schema::create('children', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('age');
$table->string('gender');
$table->timestamps();
});
}
答案 0 :(得分:1)
unsignedInteger
是创建列的函数,您不应在现有列上调用它。
// This creates an unsigned integer column.
$table->unsignedInteger('child_id');
答案 1 :(得分:0)
请确保您的子代迁移在发起人迁移之前进行,然后此列应为:
$table->unsignedInteger('child_id');
// or
$table->integer('child_id')->unsigned();