外键约束添加错误
[Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `users` add constraint `users_role_id_foreign` foreign key (`role_id`) references `role s` (`id`) on delete cascade on update cascade) [PDOException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
解决方案
1. 将欲添加外键约束的数据表 migration 文件放在参考表 migration 之后(通过文件重命名方式),如下,
并在命令行运行(此项操作很重要)
composer dump-autoload
刷新 autoload-classmap
2. 需确认添加外键约束的字段与参考字段其字段属性必须相同,如下:
// 外键约束 $table->foreign('role_id')->references('id')->on('roles')->onUpdate('cascade')->onDelete('cascade');
这句代码代码的欲添加外键约束的表是 users ,表字段是 role_id ;参考表是 roles ,参考字段是 roles 的 id 。
修改数据表默认存储引擎
在 migration 文件内添加一句代码来指定数据库引擎(将存储引擎改成InnoDB,支持事务处理):
$table->engine=’InnoDB’;