在laravel 5.6中迁移迁移时的外键问题

时间:2019-07-02 08:42:27

标签: laravel mysqli migration

我正在使用Laravel 5.6应用程序,其中我有2个表,主要是sponsors表和children表。在迁移表之间创建一对多关系。一个孩子可能有很多赞助商。  问题是使用php artisan migrate命令迁移它们时出现此错误:

  

Illuminate \ Database \ QueryException:SQLSTATE [HY000]:常规错误:   1005无法创建表larangular#sql-520c_21f(错误号:150   “外键约束格式不正确”)(SQL:alter table   sponsors添加约束sponsors_child_id_foreign外键   (child_id)在删除级联上引用了childrenid

赞助商迁移

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();
    });
}

2 个答案:

答案 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();