违反完整性约束:1451 无法删除或更新父行:外键约束失败(SQL:如果存在“问题”,则删除 table)

Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (SQL: drop table if exists `questions`)

我每次 运行 php artisan migrate::rollback 都会遇到这个问题,但当我 运行 php artisan migrate

时似乎没问题

违反完整性约束:1451 无法删除或更新父行:外键约束失败(SQL:如果存在则删除 table questions

这是我在 create_questions_table 上的迁移看起来像

public function up()
{
    Schema::create('questions', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('text');
        $table->foreignId('user_id')->constrained('users')->onDelete('cascade');
        $table->timestamps();            
    });
}

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

这是我的 create_users_table

public function up()
{
    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();
    });
}

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

这是我的迁移命令,如果你想知道的话 [https://i.stack.imgur.com/oIikb.png][1]

如果有人能帮助我我会很高兴,对不起我的英语不好

当你 运行 php artisan:rollback 它没有删除 dropForeign

也这样做

public function down()
{
    Schema::table('questions', function (Blueprint $table) {
        $table->dropForeign('user_id');
    });
    Schema::dropIfExists('questions');
}

或者因为您已经回滚了,所以您可以 dropForeign 像这样

public function up()
{
    Schema::create('questions', function (Blueprint $table) {
        $table->dropForeign('user_id');

        $table->id();
        $table->string('title');
        $table->text('text');
        $table->foreignId('user_id')->constrained('users')->onDelete('cascade');
        $table->timestamps();            
    });
}

那么你可以 运行 php artisan migrate 如果 foreign 已经存在那么只有