我正在尝试在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');
});
}
答案 0 :(得分:0)
因为您的users
中已经有users database table
行。
为此,您应该将这些新字段city_id
和province_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');
});
}