Laravel 5.8 添加外键的架构不起作用

Laravel 5.8 Schema adding foreign key not working

我正在尝试在 Laravel 5.8 中创建外键,当我使用 Artisan 迁移我的 table 时,未设置外键。在citiestable和provincestable中,所有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');
    });
}

因为您的 users database table 中已经有 users 行。 为此,您应该将这些新字段 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');
    });
}