首页 > 解决方案 > 1215 一般错误:无法添加外键约束 Laravel

问题描述

我有一个已经创建外键约束的表:

错误:

 SQLSTATE[HY000]: General error: 1215 Cannot add foreign key 
constraint (SQL: alter table `league_seasons` add 
constraint `league_seasons_league_id_foreign` foreign key (`league_id`)
 references `leagues` (`id`) on delete cascade)

这是排行榜

public function up() {
        Schema::create('leagues', function (Blueprint $table) {
            $table->integer('id');
            $table->increments('increment_id');
            $table->string('type')->nullable();
            $table->integer('legacy_id')->nullable();
            $table->integer('country_id')->nullable();
    }

这是league_seasons 表

    public function up() {
        Schema::create('league_seasons', function (Blueprint $table) {
            $table->integer('id');
            $table->increments('increment_id');
            $table->string('name')->nullable();
            $table->unsignedInteger('league_id');
            $table->string('is_current_season')->nullable();
            $table->string('current_round_id')->nullable();
            $table->string('current_stage_id')->nullable();
            App\Helpers\DbExtender::defaultParams($table, true);
        });

        Schema::table('league_seasons', function (Blueprint $table) {
            $table->foreign('league_id')->references('id')->on('leagues')->onDelete('cascade');

        });

    }

我试过交换 unSignedInteger、BigInteger 但它们似乎都没有工作。知道为什么会这样吗?谢谢

标签: phpmysqllaravel

解决方案


As @repat pointed out, adding unSignedInteger with index() on both table worked for me.

final league table:

public function up() {
        Schema::create('leagues', function (Blueprint $table) {
            $table->unsignedInteger('id')->index();
            $table->increments('increment_id');
            $table->string('type')->nullable();
            $table->integer('legacy_id')->nullable();
            $table->integer('country_id')->nullable();
            $table->string('name')->nullable();
    }

final league_seasons table:

    public function up() {
        Schema::create('league_seasons', function (Blueprint $table) {
            $table->integer('id');
            $table->increments('increment_id');
            $table->string('name')->nullable();
            $table->unsignedInteger('league_id')->index();
            $table->string('is_current_season')->nullable();
            $table->string('current_round_id')->nullable();
            $table->string('current_stage_id')->nullable();
            App\Helpers\DbExtender::defaultParams($table, true);
        });

        Schema::table('league_seasons', function (Blueprint $table) {
            $table->foreign('league_id')->references('id')->on('leagues')->onDelete('cascade');

        });

    }


推荐阅读