mafortis
mafortis

Reputation: 7128

laravel migration SQLSTATE[HY000]

I cannot run my migration command due to this error:

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)

Code

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.

Any idea?

Upvotes: 2

Views: 112

Answers (1)

Remul
Remul

Reputation: 8252

The problem is that the types for your primary and foreign key columns don't match.

Your primary key columns are UUID and your foreign key columns are BIGINT.

Changing the following should solve the error:

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

to

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

Upvotes: 2

Related Questions