【问题标题】:Laravel throws General error: 1215 Cannot add foreign key constraint" when I create foreign keysLaravel 在创建外键时抛出一般错误:1215 无法添加外键约束
【发布时间】:2020-03-09 18:36:12
【问题描述】:

我正在使用 Laravel 6。我创建了一些迁移,但我不能让它们成功运行。这些是我的迁移。

    public function up()
{
    Schema::create('nationalities', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->timestamps();
        $table->engine = "InnoDB";
    });


    public function up()
{
    Schema::create('genders', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->timestamps();
        $table->engine = "InnoDB";
    });


    public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('firstname');
        $table->string('lastname');
        $table->string('street');
        $table->string('zip');
        $table->string('city');
        $table->date('birthdate');
        $table->string('gender');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
        $table->unsignedBigInteger('gender_id');
        $table->unsignedBigInteger('nationality_id');
        $table->engine = "InnoDB";
        $table->foreign('gender_id')->references('id')->on('gender');
        $table->foreign('nationality_id')->references('id')->on('nationality');
    });
}

执行 php artisan migrate 后,我收到以下错误消息:

一般错误:1215 无法添加外键约束(SQL:更改表users添加约束users_gender_id_foreign外键(gender_id)引用genderid))

我做错了什么?

【问题讨论】:

  • 你可以refer
  • 这不是问题。我将 unsignedBigInteger 用于 bigIncrements。我应该改用什么?
  • 你也看过排名第二的答案了吗?
  • 是的。 1.我为每张表使用innodb。 2. 我引用了一个现有的键 3. 列的类型相同 4. PK 或 FK 不是 varchar。你想告诉我什么?
  • 尝试单独运行每个迁移。有时当我尝试运行这样的迁移时,它会在运行它所引用的表之前尝试运行具有外键的迁移。因此,当您单独运行它们时,先执行没有外键的那些,然后再运行外键,看看是否有帮助

标签: mysql laravel foreign-keys


【解决方案1】:

您的表名是genders 不是gendernationalities 不是nationality

变化:

...->references('id')->on('gender');
...->references('id')->on('nationality');

收件人:

...->references('id')->on('genders');
...->references('id')->on('nationalities');

【讨论】:

    猜你喜欢
    • 2021-09-28
    • 2020-06-12
    • 2019-12-27
    • 1970-01-01
    • 2018-07-29
    • 2019-09-08
    • 2021-03-29
    • 2018-07-29
    • 1970-01-01
    相关资源
    最近更新 更多