gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:02:50 26 4
gpt4 key购买 nike

我已经启动了一个新的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com