-1

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.

Tim Lewis
  • 27,813
  • 13
  • 73
  • 102
echocage
  • 1
  • 1
  • 3

1 Answers1

0

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();
        });
Mohammad Edris Raufi
  • 1,393
  • 1
  • 13
  • 34
  • Alas, it doesn't work, I still get the 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 on update cascade) – echocage Feb 13 '23 at 16:30
  • could you please share the file name of these two table migrations so I could see which table migrates first – Mohammad Edris Raufi Feb 13 '23 at 16:36
  • 2023_01_27_211654_user_files.php and 2023_01_30_192213_files.php – echocage Feb 13 '23 at 16:37
  • rename your user_files migrations to `2023_01_30_192214_user_files.php` it because your file_users migration run first before your files migration – Mohammad Edris Raufi Feb 13 '23 at 16:43
  • happy to solve your problem – Mohammad Edris Raufi Feb 13 '23 at 16:48