I have two tables in MySQL, named manuals
and library
. Both could have uploaded files, so I have made an third table, named files
. In files, I have a column parent_id. Can I make parent_id as foreign key from both manuals and library?
I am using Laravel (4.2) and tried this, but it doesn't work:
$table->integer('parent_id')->unsigned();
$table->foreign('parent_id')->references('id')->on('library');
$table->foreign('parent_id')->references('id')->on('manuals');
No. You cannot have multiple foreign keys on the same column. From the MySQL documentation:
MySQL supports foreign key references between one column and another within a table. (A column cannot have a foreign key reference to itself.) In these cases, “child table records” really refers to dependent records within the same table.
The reason for this is that MySQL won't be able to differentiate between the parents. Laravel (or any other framework) does not provide a work around for this issue.
This question as been asked in slightly different forms before. Example: it is possible to reference one column as multiple foreign keys