我在 MySQL 中有两个表,名为 manuals
和 library
。两者都可以上传文件,所以我创建了第三个表,名为 files
。在文件中,我有一列 parent_id。我可以从手册和库中将 parent_id 作为外键吗?
我正在使用 Laravel (4.2) 并尝试了这个,但它不起作用:
$table->integer('parent_id')->unsigned();
$table->foreign('parent_id')->references('id')->on('library');
$table->foreign('parent_id')->references('id')->on('manuals');
最佳答案
没有。同一列上不能有多个外键。来自 MySQL 文档:
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.
这是因为 MySQL 无法区分父节点。 Laravel(或任何其他框架)不提供解决此问题的方法。
这个问题之前的形式略有不同。示例:it is possible to reference one column as multiple foreign keys
关于mysql - 一列上的两个外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31649074/