HABTM带有用于配方成分的附加列 [英] HABTM with additional columns for recipe ingredients
问题描述
对于我的食谱共享网站,我想为该食谱及其配料创建一个数据库和CakePHP模型。
For my recipe-sharing website, I want to create a database and CakePHP models for the recipes and their ingredients.
我创建了两个表:食谱和配料。第三个表是用于Ingredients_recipes的HABTM表,该表还存储了配方所需的配料量。如何为第三张表创建模型?
I created two tables: recipes and ingredients. The third table is a HABTM table for ingredients_recipes, which also stores the amount of ingredients needed for the recipes. How do I create a model for the third table?
第三张表应如下所示:
recipe_id
Ingredient_id
金额
measurement_unit
我还考虑过为Measurement_units添加另一个表来存储所有可能的单位(例如汤匙,茶匙,杯子等)。
I also thought of adding another table for measurement_units to store all possible units (ex. tablespoon, tea spoon, cup, etc.). Would that be too much?
推荐答案
在Cake的ORM中,HABTM实际上是以下两个模型关联结构的抽象(使用您的示例):
HABTM, within Cake's ORM, is actually an abstraction of the following two model association structures (using your example):
Recipe
-> hasMany IngredientsRecipe
-> belongsTo Ingredient
和
Ingredient
-> hasMany IngredientsRecipe
-> belongsTo Recipe
推断出 IngredientsRecipe
模型,并且仅用于链接两个一流模型,即 Ingredient
和 Recipe
。
The IngredientsRecipe
model is inferred, and used only to link the two first-class models, Ingredient
and Recipe
.
但是,在您的情况下,您实际上想要 IngredientsRecipe
成为一流的模型,这破坏了HABTM抽象。实际上,您需要做的是明确定义上面的两个关联结构,以便Cake将 IngredientsRecipe
模型视为一等公民,允许您对其进行查询,将记录保存到其中,等等。
However, in your case, you actually want IngredientsRecipe
to be a first-class model, which breaks the HABTM abstraction. In fact, what you need to do is explicitly define the two association structures above, so that Cake treats the IngredientsRecipe
model as a first-class citizen, allowing you to query against it, save records to it, etc.
此外,不,我认为创建一个额外的 MeasurementUnit $ c并不过分$ c>模型。它将为您提供更大的灵活性。
Also, no, I don't think it's too much to create an additional MeasurementUnit
model. It will provide you much more flexibility down the line.
这篇关于HABTM带有用于配方成分的附加列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!