php - 使用 Laravel 迁移添加外键约束

标签 php mysql laravel laravel-5 database-migration

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

General error: 1215 Cannot add foreign key constraint (SQL: alter table users add constraint users_organization_id_foreign foreign key (organization_id) references organizations (id) on delete cascade)

下面是 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`)

最佳答案

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

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

2014_01_01_000000_create_organizations_table.php

关于php - 使用 Laravel 迁移添加外键约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46852860/

相关文章:

mysql - Azure中的Joomla-添加VirtueMart,错误502

laravel - Composer 卡在 4.2 上的 "Resolving dependencies through SAT"

php - PDO::准备安全

php - 遍历数据库

php - Class::DBI 类 php 库?

php - 一些 Facebook 用户的数据未插入 mysql 数据库

php - Netbeans PHP 项目 Apache 设置 -

mysql - 比较 mySQL 中的多个日期

php - 拉拉维尔 5.8 : Parameter passed to the event listener is getting null

laravel - 如何在 Laravel 中的 get() 之后对集合进行分页?