简体   繁体   中英

Laravel - Cannot add foreign key constraint

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. 在此处输入图片说明 在此处输入图片说明

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 ))

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM