【问题标题】:Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (SQL: drop table if exists `questions`) [duplicate]完整性约束违规:1451 无法删除或更新父行:外键约束失败(SQL:如果存在“问题”,则删除表)[重复]
【发布时间】:2021-06-14 13:30:45
【问题描述】:

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

完整性约束违规:1451 无法删除或更新父行:外键约束失败(SQL: drop table if exists 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 laravel migration


    【解决方案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 已经存在那么只有

    【讨论】:

    • 提前谢谢,这个问题我已经解决了原来我新建了一个新表,在questions表中有foreign,新表在up and down函数中有错字哈哈哈
    猜你喜欢
    • 2022-09-23
    • 2020-08-10
    • 2019-10-24
    • 2021-10-12
    • 1970-01-01
    • 2018-05-21
    • 1970-01-01
    • 2018-08-13
    • 1970-01-01
    相关资源
    最近更新 更多