【问题标题】:I have an error when migrating my tables in laravel在 laravel 中迁移表时出现错误
【发布时间】:2018-05-03 04:38:59
【问题描述】:

使用命令行迁移时,出现此错误...

(errno: 150 "Foreign key con straint is incorrectly formed")

这是我的迁移代码..

public function up()
{
    Schema::enableForeignKeyConstraints();
    Schema::create('student', function (Blueprint $table) {
        $table->integer('student_id')->unsigned()->primary();
        $table->string('student_name', 200);
        $table->string('student_email', 50);
        $table->integer('class_id')->unsigned()->nullable();
        $table->string('password', 100);
        $table->rememberToken();
        $table->timestamps();
    });

    Schema::table('student', function($table) {
       $table->foreign('class_id')->references('class_id')->on('class_tbl');
    });
}

我还没有找到解决方案,我不知道出了什么问题......

编辑:

这是 class_tbl 的迁移...

public function up()
{
  Schema::enableForeignKeyConstraints();
  Schema::create('class_tbl', function (Blueprint $table) {
    $table->integer('class_id')->unsigned()->primary();
    $table->string('course', 10);
    $table->string('section', 5);
    $table->string('school_year', 10);
    $table->integer('prof_id')->unsigned();
  });

  Schema::table('class_tbl', function($table) {
    $table->foreign('prof_id')->references('prof_id')->on('professor');
  });
}

【问题讨论】:

  • 能否请您添加 class_tbl 的迁移? &迁移发生的顺序是什么?当学生尝试引用它时,class_tbl 是否已迁移? stackoverflow.com/questions/32669880/… 迁移顺序与文件名上的数字键有关。
  • 我相信student_tbl是先被迁移的,我是否必须重新进行迁移? @admcfajn
  • 不应该重新进行迁移。不确定...
  • 我知道我是对的,我不知道是什么原因造成的。但是我会重新进行迁移,看看它是否会起作用......
  • 您是在进行基本迁移,还是构建到具有无法删除的预先存在的表的系统上?如果您还处于模型阶段,删除所有表格会非常有用。

标签: php mysql database laravel migration


【解决方案1】:

嗯...一个可以为空的外键?试试这个……

Schema::create('student', function (Blueprint $table) {
        $table->integer('student_id')->unsigned()->primary();
        $table->string('student_name', 200);
        $table->string('student_email', 50);
        $table->integer('class_id')->unsigned();
        $table->foreign('class_id')->references('class_id')->on('class_tbl');
        $table->string('password', 100);
        $table->rememberToken();
        $table->timestamps();
    });

   Schema::create('class_tbl', function (Blueprint $table) {
    $table->integer('class_id')->unsigned()->primary();
    $table->string('course', 10);
    $table->string('section', 5);
    $table->string('school_year', 10);
    $table->integer('prof_id')->unsigned();
    $table->foreign('prof_id')->references('prof_id')->on('professor');
  });

【讨论】:

    猜你喜欢
    • 2016-04-02
    • 1970-01-01
    • 2018-05-02
    • 2020-08-02
    • 1970-01-01
    • 2017-02-21
    • 2021-10-20
    • 2018-03-06
    • 1970-01-01
    相关资源
    最近更新 更多