0

I have multiple migrations but the two which I think are relevant to this question are the 'job' and 'session' migrations.

Job Migration

    Schema::create('job', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->timestamps();
    });

Sessions Migration:

    Schema::create('session', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('user_id');
        $table->unsignedBigInteger('group_id');
        $table->unsignedBigInteger('job_id');
        $table->boolean('verified')->default(0);
        $table->date('date');
        $table->time('start_time');
        $table->time('end_time');
        $table->string('session_type');
        $table->timestamps();

        $table->foreign('user_id')->references('id')->on('users');
        $table->foreign('group_id')->references('id')->on('group');
        $table->foreign('job_id')->references('id')->on('job');
    });

Now the error I get when I make migration is:

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table session add constraint session_job_id_foreign foreign key (job_id) references job (id))

Database: MySQL

I don't understand what the issue is here. This approach has always worked for me, even in this current Laravel project.

4
  • 1
    Are the migrations in the correct order? Commented Sep 19, 2019 at 11:43
  • Not sure what you mean. I did create the session migration first and then the job migration. Could that be the issue? Commented Sep 19, 2019 at 11:46
  • 1
    That's the issue. You try to create a foreign key to a table that doesn't exist. Try renaming the migration files by altering the date. Commented Sep 19, 2019 at 11:49
  • Okay, yep that worked. Thanks a lot. Commented Sep 19, 2019 at 11:50

2 Answers 2

0

You have to make sure that the that the job migration comes before session migration

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, thanks for that. Simply incrementing the timestamp to a later date works.
0

While dealing with migration and foreign key relationship (parent- child), the sequence defined on the basis of timestamp of migration file so always make sure the Parent table migration is created before the Child table. This is important because if the parent table doesn't exist means the column which you are referring in the Child table is not exist and in that case it will through such errors.

In your case changing the timestamp will solve the problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.