0

I'm trying to create a fk between tow tables. Here are my migrations:

 public function up()
    {
        Schema::create('contracts', function (Blueprint $table) {
            $table->increments('id');
            // Some other cols removed for this post
            $table->string('user_file_path');
            $table->timestamps();
            $table->foreign('user_file_path')->references('path')->on('user_files');
        });
    }

and

public function up()
    {
        Schema::create('user_files', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('application_id')->unsigned();
            $table->string('random', 32);
            $table->string('path');
            $table->timestamps();
            $table->foreign('application_id')->references('id')->on('applications');
        });
    }

I get this error after running php artisan migrate

 General error: 1005 Can't create table 'dashboard'.'#sql-1890_b6' (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table 'contracts' add constraint 'contracts_user_file_path_foreign' foreign key ('user_file_path') references 'user_files' ('path'))

What am I doing wrong?

Markus
  • 1,909
  • 4
  • 26
  • 54
  • 1
    You've not set an index on the 'path' column in "user_files" table. Anyway, you why don't you reference by the user_file_id? – MyLibary Oct 18 '18 at 17:22

1 Answers1

1

Why don't you reference the user_files record by id e.g.

public function up()
{
    Schema::create('contracts', function (Blueprint $table) {
        $table->increments('id');
        // Some other cols removed for this post
        $table->integer('user_file_id')->unsigned();
        $table->timestamps();
        $table->foreign('user_file_id')->references('id')->on('user_files');
    });
}
Question Mark
  • 3,557
  • 1
  • 25
  • 30