SQLSTATE [HY000]:一般错误:1215 - 即使使用'InnoDB'和无符号

时间:2018-05-24 14:52:14

标签: laravel laravel-5 laravel-migrations

我正在尝试在country_id字段上创建一个外键,从domains表到id countries字段。但是当我进行迁移时:php artisan migrate:fresh

错误讯息:

Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `domains` add constraint `domains_country_id_foreign` foreign key (`country_id`) references `countries` (`id`) on delete cascade)

以下是domains迁移文件:

public function up()
{
    Schema::create('domains', function (Blueprint $table) {
        $table->increments('id');
        $table->string('code');
        $table->string('name');
        $table->string('display_name');
        $table->string('extension');
        $table->string('google_analytics')->nullable();
        $table->string('google_webmastertool')->nullable();
        $table->string('google_maps')->nullable();
        $table->integer('country_id')->unsigned();
        $table->boolean('actif')->default(true);
        $table->timestamps();
        $table->engine = 'InnoDB';
    });

    Schema::table('domains', function (Blueprint $table) {
        $table->foreign('country_id')->references('id')->on('countries')->onDelete('cascade');
    });
}

这是countries迁移文件:

public function up()
{
    Schema::create('countries', function (Blueprint $table) {
        $table->increments('id');
        $table->string('code');
        $table->string('name');
        $table->string('alpha2', 2);
        $table->string('alpha3', 3);
        $table->timestamps();
        $table->engine = 'InnoDB';
    });
}

正如您所看到的,country_id字段是无符号的,表引擎是InnoDB。我已经使用外键进行了其他迁移,它们工作正常,但是这个不起作用:|

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

来自@Bogdan的解决方案。

使用迁移文件的时间戳更改迁移顺序。 您需要使用外键的文件具有高时间戳,而不是主键所在的迁移文件的时间戳。