首页 > 解决方案 > 在迁移 [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`))

我听说并知道如果两种数据类型不同,就会发生此错误,因为我之前遇到过这个问题并通过确保两种数据类型相同来设法解决它。但我认为数据类型已经相同了吧?我错过了什么吗?还是问题不在于数据类型?谢谢!

标签: laravellaravel-8

解决方案


此问题的已知原因是顺序,如果您的“用户”迁移文件在“配置文件”迁移文件之前运行,则可能会发生这种情况。

解决方案是更改迁移文件名,以便“配置文件”迁移文件首先运行。


推荐阅读