我应该可以将外键参考添加到枢轴表



我有三个表菜单,食物,菜单_food,我有以下迁移代码来创建表菜单菜单

$table->increments('id');
$table->timestamps();
$table->integer('food_id');
$table->integer('menu_id');

桌子食品,菜单也有两个增量ID。

我想知道我是否应该在food_id和菜单上添加外国密钥作为菜单表和食物表的ID的参考?

-----更新-------
我尝试了答案,但是有错误

php工匠迁移

  [IlluminateDatabaseQueryException]
  SQLSTATE[HY000]: General error: 1005 Can't create table `laravel_foodcall`.
  `#sql-198c_1e1` (errno: 150 "Foreign key constraint is incorrectly formed")
   (SQL: alter table `menu_food` add constraint `menu_food_food_id_foreign` f
  oreign key (`food_id`) references `food` (`id`))

  [PDOException]
  SQLSTATE[HY000]: General error: 1005 Can't create table `laravel_foodcall`.
  `#sql-198c_1e1` (errno: 150 "Foreign key constraint is incorrectly formed")

是的,您需要添加 foreign键作为相应表id的参考。这样的东西:

$table->foreign('food_id')->references('id')->on('food');
$table->foreign('menu_id')->references('id')->on('menu');

您可以在此处查看Laravel文档

最新更新