HABTM with optional columns for recipe ingredients

For my recipes exchange site, I want to create a CakePHP database and model for recipes and their ingredients.

I created two tables: recipes and ingredients. The third table is the HABTM table for ingredients, which also contain the amount of ingredients needed for recipes. How to create a model for the third table?

The third table will look something like this:

recipe_id
ingredient_id
amount
measurement_unit

I also thought about adding another table for measuring_units to store all possible units (like a tablespoon, teaspoon, cup, etc.). Would it be too much?

+1
source share
2 answers

HABTM, inside Cake ORM, is actually an abstraction of the following two model association structures (using your example):

 Recipe -> hasMany IngredientsRecipe -> belongsTo Ingredient 

and

 Ingredient -> hasMany IngredientsRecipe -> belongsTo Recipe 

The IngredientsRecipe model is inferred and used only to link the two first-class Ingredient and Recipe models.

However, in your case, you really want IngredientsRecipe be a first-class model, which violates the HABTM abstraction. In fact, you need to explicitly define the two relationship structures above, so Cake treats the IngredientsRecipe model as a first-class citizen, allowing you to query it, save records to it, etc.

Also, no, I don’t think it's too much to create an additional MeasurementUnit model. This will provide you with great flexibility along the line.

+4
source

Think of it this way, and then process it in one piece at a time:

 `Recipe` (1)--(n) IngredientsRecipe (n)--(1) Ingredient 
  • In Recipe create a link to IngredientsRecipe
  • In Ingredient create a relationship with IngredientsRecipe
  • In IngredientsRecipe create a link to Recipe
  • Still at IngredientsRecipe create a link to Ingredient

For now, forget about HABTM and think about hasMany and belongsTo

By the way, you are not required to call the IngredientsRecipe model, which is standard / conditional.

When you're done, treat it like hasMany, belongs to, or HABTM, if necessary.

+2
source

All Articles