hkguile hkguile - 5 months ago 17
SQL Question

should can i add foreign key reference to a pivot table

i have three tables menu, food, menu_food, i have the following migration code to create a table menu_food

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


The table food, menu also has two increment id.

i'm wondering should i add foreign keys on food_id and menu_id as reference to id of the menu table and food table?

-----update------

i've tried the answer but has errors

php artisan migrate

[Illuminate\Database\QueryException]
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")

Answer

Yes, you need to add foreign keys as reference to respective table id. Something like this:

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

You can see the Laravel documentation here.

Comments