数据迁移无法添加外键约束,错误代码 1215
错误问题排除项:
1、两个字段类型必须一致
2、数据库引擎InnoDB
3、原有数据表字段必须已加索引(重要)
例错误代码:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `user_addresses` add constraint `user_addr
esses_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)
解析:
原users表默认id已是主键,默认情况是不会出现上面错误的,但是像我爱折腾,users表用uid表示用户识别码,未设置索引,导致迁移表时报错1215。
解决办法:
新建users表uid字段时加上索引index()
$table->bigInteger('uid')->index()->after('id');
本作品采用《CC 协议》,转载必须注明作者和本文链接
现在喜欢松耦合,不做这种强外键约束。
@xuanjiang1985 刚刚学习Laravel,还忘多多指点,还没入门呢