HABTM 带有额外的配方成分列
对于我的食谱共享网站,我想为食谱及其成分创建一个数据库和 CakePHP 模型。
我创建了两个表:食谱和成分。第三个表是配料_食谱的 HABTM 表,它还存储食谱所需的配料数量。如何为第三个表创建模型?
第三个表看起来像这样:
recipe_id
成分_id
金额
measurement_unit
我还考虑为measurement_units添加另一个表来存储所有可能的单位(例如汤匙、茶匙、杯子等)。会不会太多了?
For my recipe-sharing website, I want to create a database and CakePHP models for the recipes and their ingredients.
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?
The third table would look something like this:
recipe_id
ingredient_id
amount
measurement_unit
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Cake 的 ORM 中,HABTM 实际上是以下两个模型关联结构的抽象(使用您的示例):
并且
IngredientsRecipe 模型是推断出来的,并且仅用于链接两个一流模型,<代码>成分和
食谱
。然而,就您的情况而言,您实际上希望
IngredientsRecipe
成为一流的模型,这打破了 HABTM 抽象。事实上,您需要做的就是显式定义上面的两个关联结构,以便 Cake 将 IngredientsRecipe 模型视为一等公民,允许您对其进行查询、将记录保存到其中,另外,不,我认为创建额外的
MeasurementUnit
模型并不过分。它将为您提供更大的灵活性。HABTM, within Cake's ORM, is actually an abstraction of the following two model association structures (using your example):
and
The
IngredientsRecipe
model is inferred, and used only to link the two first-class models,Ingredient
andRecipe
.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 theIngredientsRecipe
model as a first-class citizen, allowing you to query against it, save records to it, etc.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.可以这样想,然后一次处理一小块:
Recipe
中,创建与IngredientsRecipe
的关联Ingredient
中,创建与IngredientsRecipe
IngredientsRecipe
中创建与Recipe
的关联IngredientsRecipe
中创建与Ingredient
的关联>在执行此操作时,请忘记 HABTM,而考虑
hasMany
和belongsTo
顺便说一句,您不必调用模型 IngredientsRecipe,这只是默认值/习俗。
完成后,根据需要将其视为 hasMany、belongsTo 或 HABTM。
Think of it like this then treat it one chunk at a time:
Recipe
, create the association toIngredientsRecipe
Ingredient
, create the association toIngredientsRecipe
IngredientsRecipe
create the association toRecipe
IngredientsRecipe
create the association toIngredient
While you're doing it, forget about HABTM and think instead about
hasMany
andbelongsTo
Incidentally, you are not bound to call the model IngredientsRecipe, that is just the default/convention.
When you're done, treat it like hasMany, belongsTo or HABTM as appropriate.