Laravel 5.8模式添加外键不起作用

时间:2019-05-03 14:19:15

标签: laravel-5 laravel-5.8 laravel-schema-builder

我正在尝试在Laravel 5.8中创建外键,而当我使用Artisan迁移表时,未设置外键。在cities表和provinces表中,所有id字段均为无符号整数。我正在Windows 10上使用wamp64。

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->integer('city_id')->unsigned();
        $table->integer('province_id')->unsigned();
        // table Foreign Key
        $table->foreign('city_id')->references('id')->on('cities');
        $table->foreign('province_id')->references('id')->on('provinces');
    });
}

1 个答案:

答案 0 :(得分:0)

因为您的users中已经有users database table行。 为此,您应该将这些新字段city_idprovince_id设为nullable作为默认值。

因此您的迁移应如下所示:

public function up()
{
    Schema::table('users', function (Blueprint $table) {

         // I have added here nullable for both city_id and province_id

        $table->integer('city_id')->unsigned()->nullable();
        $table->integer('province_id')->unsigned()->nullable();
        // table Foreign Key
        $table->foreign('city_id')->references('id')->on('cities');
        $table->foreign('province_id')->references('id')->on('provinces');
    });
}
相关问题