laravel 迁移 SQLSTATE[HY000]

laravel migration SQLSTATE[HY000]

由于这个错误,我无法 运行 我的迁移命令:

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table user_schools add constraint user_schools_school_id_foreign foreign key (school_id) references schools (id) on delete cascade)

代码

users

 Schema::create('users', function (Blueprint $table) {
        $table->uuid('id')->primary();
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->softDeletes('deleted_at', 0);
        $table->timestamps();
 });

schools

Schema::create('schools', function (Blueprint $table) {
        $table->uuid('id')->primary();
        $table->string('code')->unique();
        $table->string('name');
        $table->set('type', ['TK', 'SD', 'SMP', 'SMA', 'SMK']);
        $table->softDeletes('deleted_at', 0);
        $table->timestamps();
});

user_schools

Schema::create('user_schools', function (Blueprint $table) {
        $table->uuid('id')->primary();
        $table->foreignId('school_id')->constrained('schools')->onDelete('cascade');
        $table->foreignId('user_id')->constrained('users')->onDelete('cascade');
        $table->set('type', ['Manager', 'Staff', 'Teacher', 'Student']);
        $table->softDeletes('deleted_at', 0);
        $table->timestamps();
});

NOTE: My migration files are based on laravel documentation yet I'm getting this error.

有什么想法吗?

问题是您的主键和外键列的类型不匹配。

您的主键列是 UUID,您的外键列是 BIGINT

更改以下内容应该可以解决错误:

$table->foreignId('school_id')->constrained('schools')->onDelete('cascade');

$table->uuid('school_id')->constrained('schools')->onDelete('cascade');