Search code examples
phplaravellaravel-migrations

Foreign key constraint is incorrectly formed (with inno db)


When running:

Schema::create('files', function (Blueprint $table) {
  $table->engine = 'InnoDB';
  $table->id();
  $table->string('path');
  $table->timestamps();
});
Schema::create('file_users', function (Blueprint $table) {
  $table->engine = 'InnoDB';
  $table->id();
  $table->integer('file_id');
  $table->foreign('file_id')->references('id')->on('files')->onDelete('cascade');
  $table->mediumInteger('user_id');
  $table->timestamps();
});

I'm getting error:

SQLSTATE[HY000]: General error: 1005 Can't create table atomes.file_users (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table file_users add constraint file_users_file_id_foreign foreign key (file_id) references files (id) on delete cascade)

None of the internet answers helped me.

I tried changing the table types to myISAM but that didn't work for me.


Solution

  • try this

            Schema::create('file_users', function (Blueprint $table) {
                $table->engine = 'InnoDB';
                $table->id();
                $table->foreignId('file_id')->nullable(true)->constrained('files')->onUpdate('cascade')->onDelete('cascade');
                $table->foreignId('user_id')->constrained('users');
                $table->timestamps();
            });