编程语言
首页 > 编程语言> > php-使用Laravel迁移添加外键约束

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

作者:互联网

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

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)

这是组织表的迁移代码:

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中创建新安装用户表.但是,由于要在此表中添加约束,因此需要首先创建组织表.

因此,通过在文件名中更改组织迁移日期,将组织表迁移放在用户表迁移之前:

2014_01_01_000000_create_organizations_table.php

标签:laravel,laravel-5,database-migration,mysql,php
来源: https://codeday.me/bug/20191025/1929920.html