【问题标题】:Laravel migrations change foreign key to be nullOnDelete() and nullable(true)Laravel 迁移将外键更改为 nullOnDelete() 和 nullable(true)
【发布时间】:2023-02-06 03:34:58
【问题描述】:

我有这个迁移,我第一次创建了一个外键:

        Schema::table('user_plays_quizzes', function (Blueprint $table) {
            $table->bigInteger('quiz_id')->unsigned()->change();
            $table->foreign('quiz_id')->references('id')->on('quizzes');
        });

现在我有一个新的迁移,我想将这个外键更新为nullable(true)nullOnDelete()

试了很多次,总是报错,感觉最接近的做法是:

        Schema::table('user_plays_quizzes', function (Blueprint $table) {
            $table->bigInteger('quiz_id')->unsigned()->nullable(true)->change();
            $table->foreign('quiz_id')->references('id')->on('quizzes')->nullOnDelete();
        });

可悲的是它也不起作用:

SQLSTATE[HY000]: General error: 1005 Can't create table `d039e62e`.`user_plays_quizzes` (errno: 121 
"Duplicate key on write or update") (SQL: alter table `user_plays_quizzes` add constraint `user_plays_quizzes_quiz_id_foreign` for
eign key (`quiz_id`) references `quizzes` (`id`) on delete set null)

不知道如何解决它。我什至不能放下钥匙并重新创建它们。也许有人知道我如何通过迁移更新它

【问题讨论】:

    标签: laravel migration


    【解决方案1】:

    为什么不能删除密钥并重新创建它?

    public function up()
    {
        Schema::table('user_plays_quizzes', function (Blueprint $table) {
            // Drop fk constraint on quiz_id column
            $table->dropForeign(['quiz_id']);
            // Alter quiz_id column
            $table->bigInteger('quiz_id')->unsigned()->nullable(true)->change();
            // Add new fk constraint on quiz_id column
            $table->foreign('quiz_id')->references('id')->on('quizzes')->nullOnDelete();
    
        });
    }
    
    public function down()
    {
        Schema::table('user_plays_quizzes', function (Blueprint $table) {
            // Drop fk constraint on quiz_id column
            $table->dropForeign(['quiz_id']);
            // Restore quiz_id column to how it was before
            $table->bigInteger('quiz_id')->unsigned()->nullable(false)->change();
            // Restore original fk constraint on quiz_id column
            $table->foreign('quiz_id')->references('id')->on('quizzes');
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-16
      • 1970-01-01
      • 2020-06-05
      • 2014-03-11
      • 2021-06-30
      • 2011-06-16
      • 2020-02-20
      • 2016-06-06
      • 2019-09-23
      相关资源
      最近更新 更多