Migration:refresh 在尝试添加外键时抛出错误

Migration:refresh is throwing an error when trying to add a foreign key

我正在尝试向 table 添加一个外键,但是当我添加外键,然后尝试 运行 php artisan migrate:refresh 时,我不断抛出以下内容错误。

SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'properties' already exists (SQL: create table `properties` (`id` bigint unsigned not null auto_increment primary key, `created_at` timestamp null, `updated_at` timestamp null, `property_title` varchar(255) not null, `property_description` varchar(255) not null, `property_image` varchar(255) not null, `user_id` bigint unsigned not null, `id` bigint unsigned not null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')

属性迁移架构:

Schema::create('properties', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->string('property_title');
            $table->string('property_description');
            $table->string('property_image');
            $table->bigInteger('user_id')->unsigned();
            $table->foreignId('id')->constrained('users');
        });

用户迁移架构:

Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

$table->foreignId('x') 创建了一个列,所以 bigInteger 和 foreign id 行是多余的,会导致错误。

删除:

$table->bigInteger('user_id')->unsigned();

那么foreign ID应该是foreign column的名字。所以'id'应该改为'user_id'。所以你可以把最后一行改成这样:

改变

$table->foreignId('user_id')->constrained('users');

你也可以去掉最后的 'constrained('users') 并替换为 'foreignIdFor' 并且 laravel 会找出哪个 table基于列名称属于:

$table->foreignIdFor(User::class);

Here is the docs link describing this

向下函数

最后,如果迁移文件中没有 down() 函数,migrate:refesh 将无法工作。因此,请确保您包含如下功能:

public function down()
{
    Schema::dropIfExists('properties');
}

这应该与属性 table

的 'up()' 函数位于同一个文件中