php - Laravel 5.8 迁移中的外键未知(MEDIUMINT?)问题
问题描述
我在向表中添加 MEDIUMINT 外键约束时遇到问题。我知道它有效,在BASE TABLE中organization_id
也引用了 MEDIUMINT。FOREIGN TABLE中的第一个外键有效,但第二个无效。
我肯定知道的事情:
- 父表和子表都有
unsignedMediumInteger
; - 外国专栏被创建;和
- 键是在父表和外列创建之后添加的。
我尝试过的事情:
- 更改
$table->unsignedMediumInteger('customer_id');
为$table->mediumInteger('customer_id')->unsigned();
Schema::create('numberblocks')
在Schema::table('numberblocks')
同一迁移中将外键与 in 分开;- 将数据类型更改为 INT、SMALLINT;
- 在子表中将名称从
customer_id
更改为;c_id
和 - 将外键设置为自己的迁移。
基表
Schema::create('customers', function (Blueprint $table) {
$table->increments('id');
$table->unsignedMediumInteger('organization_id');
$table->unsignedMediumInteger('customer_id');
$table->string('customer_domain');
$table->timestamps();
// Foreign Keys
$table->foreign('organization_id')->references('id')->on('organizations');
});
外国表
Schema::create('numberblocks', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('group_id')->index();
$table->unsignedMediumInteger('customer_id');
$table->unsignedMediumInteger('order_id');
$table->string('number', 15);
$table->timestamps();
// Foreign Keys
$table->foreign('group_id')->references('id')->on('groups');
$table->foreign('customer_id')->references('customer_id')->on('customers');
});
我尝试过的一切都以同样的错误告终:
SQLSTATE[HY000]: General error: 1005 Can't create table 'db'.'#sql-1a78_2a6'
(errno: 150 "Foreign key constraint is incorrectly formed")
(SQL: alter table 'numberblocks' add constraint 'numberblocks_customer_id_foreign'
foreign key ('customer_id') references 'customers' ('customer_id'))```
我的问题:有没有其他人知道让这个工作的方法?
解决方案
是的,正如错误所说
一般错误:1822 无法添加外键约束。引用表'customers'中的约束'numberblocks_customer_id_foreign'缺少索引")
所以尝试添加
$table->index(['customer_id']);
在客户迁移中并将解决问题
如果不是请在下面评论
推荐阅读
- php - json更新laravel数据库中的多条记录
- sql - AEM JCR SQL2 查询以查找包含特定组件的所有页面
- mongodb - 为什么 mongo 不能将我的 ObjectId 推送到预定义的数组中?
- ios - 无法在物理设备上构建 ios 应用程序
- api - Rally API 获取特定 Epic 下的所有功能
- razor - Razor:将带有 _blank、noopener、noreffer 属性的 href 转换为 Html ActionLink
- php - 根据给定时间自动执行 php 函数,而不使用 Cron
- docker - 如何在不启动容器的情况下将 docker 映像导出到 rootfs?
- swift - 错误域=NSURLErrorDomain 代码=-999 “取消” Xcode
- node.js - 类型错误:firestoreService.snapshot_ 不是函数