首页 > 解决方案 > 为什么 laravel 显示“外键约束格式不正确”?

问题描述

我正在尝试进行 laravel 迁移并在两个表之间建立外键约束。这是我的一些代码:

创建用户教育表

class CreateUserEducationTable extends Migration
{
    public function up()
    {
        Schema::create('user_education', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onUpdate('CASCADE')
                ->onDelete('CASCADE');
            $table->unsignedBigInteger('institution_id');
            $table->foreign('institution_id')
                ->references('id')
                ->on('education_institutions')
                ->onUpdate('CASCADE')
                ->onDelete('CASCADE');
            $table->string('degree')->nullable();
            $table->string('grade')->nullable();
            $table->year('start_year')->nullable();
            $table->year("end_year")->nullable();
            $table->timestamps();
        });
    }

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

创建教育机构表

class CreateEducationInstitutionsTable extends Migration
{

    public function up()
    {
        Schema::create('education_institutions', function (Blueprint $table) {
            $table->id();
            $table->string('institution_name');
            $table->string('country');
            $table->string('city');
            $table->string('logo')->nullable();
            $table->text('description')->nullable();
            $table->timestamps();
        });
    }

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

在迁移 ```user_education_table`` 时会抛出以下错误。 在此处输入图像描述

这里有什么意义?

标签: laravellaravel-7

解决方案


您必须在创建education_institutions表之前创建user_education


推荐阅读