【问题标题】:Adding a foreign key constraint with a Laravel Migration使用 Laravel 迁移添加外键约束
【发布时间】:2018-04-01 20:19:54
【问题描述】:

我已经启动了一个新的 Laravel 5.5 项目,并且在尝试向我的 users 表添加外键时收到以下错误:

一般错误:1215 无法添加外键约束(SQL:alter table users 添加约束 users_organization_id_foreign 外键 (organization_id) 在删除级联时引用 organizations (id))

这是organization 表的迁移代码:

Schema::create('organizations', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('subdomain')->nullable();
    $table->timestamps();
    $table->softDeletes();
});

这是users 表的迁移代码:

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('organization_id')->unsigned();
    $table->foreign('organization_id')->references('id')->on('organizations');
    $table->string('first_name');
    $table->string('last_name');
    $table->string('email')->unique();
    $table->timestamps();
    $table->softDeletes();
});

我在网上研究过这个错误,要确保的共同点是数据类型是相同的。据我所知,它们是相同的。更疯狂的是,如果我直接在数据库中运行这个查询,它就可以工作:

alter table `users` add constraint `users_organization_id_foreign` foreign key (`organization_id`) references `organizations` (`id`)

【问题讨论】:

  • 你在 composer.json 中添加了 dbal 吗?如果没有添加,composer 需要学说/dbal

标签: php mysql laravel laravel-5 database-migration


【解决方案1】:

默认情况下,在每个 Laravel 全新安装中首先创建 users 表。但是由于您在此表中添加了约束,因此您需要先创建organizations 表。

因此,通过更改文件名中的organizations 迁移日期,将organizations 表迁移放在users 表迁移之前:

2014_01_01_000000_create_organizations_table.php

【讨论】:

    【解决方案2】:

    同意 Alexey 的回答。我还建议您在运行迁移之前启用/禁用外键约束:

    Schema::disableForeignKeyConstraints();
    // Your migration code.
    Schema::enableForeignKeyConstraints();
    

    这样您就无需重命名迁移文件。

    【讨论】:

      猜你喜欢
      • 2019-03-24
      • 2017-03-27
      • 1970-01-01
      • 2021-08-30
      • 2020-09-21
      • 2020-03-12
      • 2020-01-20
      • 2019-07-31
      相关资源
      最近更新 更多