I am using MySQL as the database and Eloquent as the ORM.
I have been creating a page that is about food or dishes, in which I already have the meals related to the chefs who prepare them, so that I have them like this:
Table foods
(meals)
public function up()
{
Schema::create('foods', function (Blueprint $table) {
$table->increments('id');
$table->string('title', 50);
$table->integer('creator_id')->unsigned();
$table->string('image', 300);
$table->text('description');
$table->enum('type', ['breakfast', 'lauch', 'dinner', 'snack']);
$table->enum('status', ['active', 'inactive']);
$table->timestamps();
$table->foreign('creator_id')->references('id')->on('creators');
});
}
Tablemenus
public function up()
{
Schema::create('menus', function (Blueprint $table) {
$table->increments('id');
$table->enum('dia_semana', [
'lunes',
'martes',
'miercoles',
'jueves',
'viernes',
'sabado',
'domingo',
]);
$table->timestamps();
});
}
What I want is to relate these two tables so that it is something like this: 3 foods
would be in a menu
, but those 3 meals that are in that menu can be in several menus of the day. Example:
food1, food2, food3 would be in menu1 which are on Mondays , another row: food1, food4, food5 which repeats food1 would be in menu2 on Tuesdays and so on.
I haven't figured out how to do it yet, so I need some help on how I could do that relationship in the many-to-many alternating table food_menu
.
What you really need, in my opinion, is to create an intermediate table to be able to make an N to N relationship between Food and Menu, therefore a Food can be in several Menus and a Menu can have many foods
This would generate a row for each relationship but it fulfills the operation that you want to achieve
You can do this in the following way:
Then in your Food and Menu models you make the relationship between them:
Then finally if you want to get all the foods that belong to a menu, let's say the one with id 10. You can do it in the following way.
I hope it can help you
Cheers!