laravel - 在迁移 [Laravel 8] 中添加外键时出错(错误号:150“外键约束格式不正确”)
问题描述
我有我的users
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->enum('role', ['admin', 'operator', 'owner']);
$table->string('password');
$table->foreignId('profile_id')->constrained('profile');
$table->rememberToken();
$table->timestamps();
});
我有我的profile
Schema::create('profile', function (Blueprint $table) {
$table->id();
$table->string('full_name');
$table->bigInteger('phone');
$table->string('address');
$table->enum('gender', ['men', 'women']);
});
每次我尝试迁移它都会弹出错误
SQLSTATE[HY000]: General error: 1005 Can't create table `myDatabase`.`users` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `users` add constraint `users_profile_id_foreign` foreign key (`profile_id`) references `profile` (`id`))
我听说并知道如果两种数据类型不同,就会发生此错误,因为我之前遇到过这个问题并通过确保两种数据类型相同来设法解决它。但我认为数据类型已经相同了吧?我错过了什么吗?还是问题不在于数据类型?谢谢!
解决方案
此问题的已知原因是顺序,如果您的“用户”迁移文件在“配置文件”迁移文件之前运行,则可能会发生这种情况。
解决方案是更改迁移文件名,以便“配置文件”迁移文件首先运行。
推荐阅读
- postgresql - 在 HSTORE 上创建检查约束以维护特定的数据连续性
- angular - 使用 Angular 和 Typescript 的策略模式
- php - PHP) mysqli_prepare 在 if 语句中不起作用
- ios - 每次关闭应用程序后 Xcode Firebase 身份验证都会注销
- python - 为什么我在对象检测中遇到错误?
- java-8 - 如何在没有消费者的情况下创建一个 flink 生产者作业
- python - 遍历 Pandas 数据框并获取值和行号
- angular - 在触摸控件之前显示 mat-form-field 错误消息
- grafana - 你如何在 grafana/influxql 中获得最后一次测量的年龄?
- python - 如何将 id 添加到 postgresql 中的主键?