0

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

1 回答 1

0

因为您usersusers database table. 要实现这一点,您应该将这些新字段 设置city_id为 默认值。province_idnullable

所以您的迁移应该如下所示:

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');
    });
}
于 2019-05-03T18:06:59.897 回答