Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - add foreign key on existing table with data

I have existing table objects with data. Now I need to add new table named holdings and add a relation from objects to holdings table. In the migration file, I print this:

$table->foreign('holding_id')->references('id')->on('holdings')->onDelete("NO ACTION");

and get this error when trying to migrate

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update 
a child row: a foreign key constraint fails (`kolomnaoffice`.`#sql-f10_126` 
CONSTRAINT `objects_holding_id_foreign` FOREIGN KEY (`holding_id`) 
REFERENCES `holdings` (`id`) ON DELETE NO ACTION) (SQL: alter table `objects` add constraint 
`objects_holding_id_foreign` foreign key (`holding_id`) references `holdings` 
(`id`) on delete NO ACTION)

I have correct database structure (both InnoDB), the fields exist and have correct type (int). The only thing different is that the table objects is filled with data, and table holdings is new and empty.

like image 436
Alexander Guskov Avatar asked Jun 25 '17 08:06

Alexander Guskov


2 Answers

The holding_id column should be unsigned

Create a new migration file and migrate it, migration code should be like this :

Schema::table('objects', function (Blueprint $table) {
    $table->integer('holding_id')->unsigned()->change();

    $table->foreign('holding_id')->references('id')->on('holdings');
});

The change() method is called to change the structure of existing column.

It's not necessary to call onDelete("NO ACTION") method.

like image 181
Mohammad Fanni Avatar answered Sep 24 '22 06:09

Mohammad Fanni


Thanks Mohammad but this solution didn't work for me as I am Laravel 5.4 and have different case here that my other table is already exists, Here what I found may it help some one.

Schema::table('objects', function (Blueprint $table) {
    $table->integer('holding_id')->unsigned()->index()->nullable();

    $table->foreign('holding_id')->references('id')->on('holdings');
});

with index() and nullable() it made the trick.

Edit No need for index() it just need to be nullable()

like image 43
Yousef Altaf Avatar answered Sep 20 '22 06:09

Yousef Altaf