sqlsql-servert-sql

Modelling a Meals / Recipes / Foods database


I am trying to model a database containing the following tables:

Meals (MealId)
MealRecipes (MealId, RecipeId)
MealFoods (MealId, FoodId)

Recipes (RecipeId)
RecipeFoods (RecipeId, FoodId)
Foods (FoodId)

A Recipe is composed of N Foods (Apple, Salmon, ...)

But when I build a Meal it can contain Recipes (Salmond with vegetables) but also a Food (Apple) ...

My biggest problem is with building the Meal with both Recipes and Foods.

UPDATE
One important thing is the order of the Recipes / Food in a Meal. So another approach would be:

Meals (MealId)
MealSteps (MealId, StepNumber, RecipeId, FoodId)

Where RecipeId or FoodId, either one, could be null. But not both.


Solution

  • Your solution looks fine. A meal is composed of different recipies (e.g. one for the main dish, one for the salad) plus single food (e.g. an apple for dessert).

    Another way to model this would be to drop the table MealFoods and make one-food recipies instead. (E.g. an apple by itself is a "recipe" for a simple dessert. Salt on the other hand is not.)

    So with this model you even prevent some food to be added to a meal. You could do the same with a mere flag in Foods in your model, too, that allows apple to be added to a meal and salt not. But that would rely on you to consider the flag whenever inserting into MealFoods, whereas in the second model you can only add recipes to meals, which makes this safer.

    UPDATE: Here is the proposed model. You see, I've only removed one table. (And I put in the position you have added in yor update). The trick is that you build some "recipes" that have only a single entry in RecipeFoods, e.g. an apple.