1

I am trying to add FK 'module_id' to my table 'documents'. I have ran the following query:

 public function up()
    {
        Schema::table('documents', function (Blueprint $table) {

            $table->integer('module_id')->unsigned();
            $table->foreign('module_id')->references('id')->on('modules');

        });
    }

The following error is being returned:

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table documents add constraint documents_module_id_foreign foreign key (module_id) references modules (id))

I'm not sure what I'm doing wrong, I'm sure it is probably a silly mistake but I have spent a lot of time going around in circles trying to figure it out... here is what I have tried..

  • both tables are already created
  • the data types for both column's are consistent (both unsignedBigInts, 20)

I have included a picture of my DB tables, i appreciate any help. enter image description here enter image description here

Update:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (laravel.#sql-2cd_23, CONSTRAINT documents_module_id_foreign FOREIGN KEY (module_id) REFERENCES modules (id)) (SQL: alter table documents add constraint documents_module_id_foreign foreign key (module_id) references modules (id))

0

1 Answer 1

1

The type of the column needs to be a big integer.

    Schema::table('documents', function (Blueprint $table) {
        $table->unsignedBigInteger('module_id');
        $table->foreign('module_id')->references('id')->on('modules');

    });

Update

You probably already got data in your tables, since the column can't be null the foreign key can't exists. Starting it out as nullable then adding the relationships and removing the nullable would fix it. So:

$table->unsignedBigInteger('module_id')->nullable();
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thanks for this.. i made the changes but produced an error (I've attached in my original qs... could you advise?
Thank you! I deleted the data (wasn't relatively important) and it worked. Appreciate it

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.