2010-10-27 60 views
1

对于我的食谱分享网站,我想为食谱及其配料创建一个数据库和CakePHP模型。HABTM带配方成分的额外列

我创建了两个表格:食谱和配料。第三张桌子是用于ingredients_recipes的HABTM桌子,其中还储存了配方所需的配料量。如何为第三个表格创建模型?

第三个表将是这个样子:

recipe_id
ingredient_id
amount
measurement_unit

我也想加入另一个表measurement_units存储所有可能的单位(如汤匙,茶勺,杯子等)。这太多了吗?

回答

4

HABTM,蛋糕的ORM内,实际上是(用你的例子)的以下两个模型关联结构的抽象:

Recipe 
-> hasMany IngredientsRecipe 
      -> belongsTo Ingredient 

Ingredient 
-> hasMany IngredientsRecipe 
      -> belongsTo Recipe 

IngredientsRecipe模型推断,并用仅链接两个一流车型,IngredientRecipe

然而,在你的情况,你实际上想要IngredientsRecipe是一个一流的模型,打破了HABTM抽象。事实上,您需要做的是明确定义上述两个关联结构,以便Cake将IngredientsRecipe模型视为一等公民,允许您查询它并将记录保存到它,等等。

也,不,我认为创建一个额外的MeasurementUnit模型并不算太多。它将为您提供更大的灵活性。它

+0

对不起,我想我完全失去了这一切。我如何明确定义两个关联结构?通过创建模型php文件,就像配料和食谱文件? – Olga 2010-10-27 15:31:27

+1

对不起,回到你身边。基本上,你需要定义三个模型而不是两个,因为你不是真的直接将'Recipe'和'Ingredient'联系在一起。相反,你加入'Recipe'到'RecipeElement'到'Ingredient';和'成分'到'RecipeElement'到'配方'。 “配料”和“配方”继续填充他们现在所做的相同作用,“配方元素”包含有关配方中每种配料的具体测量和单位的信息。我希望这是有道理的。 – 2010-10-28 13:06:22

+0

作为解释,我添加了一个答案,但我把我的帽子丢给了丹尼尔;) – Leo 2010-10-28 20:30:30

2

这样想着,然后把它一个大块在一个时间:

`Recipe` (1)--(n) IngredientsRecipe (n)--(1) Ingredient 
  1. Recipe,创建协会IngredientsRecipe
  2. Ingredient,创建协会IngredientsRecipe
  3. IngredientsRecipe创建关联到Recipe
  4. 仍在IngredientsRecipe创建协会Ingredient

当你这样做了,忘了HABTM和思考,而不是关于hasManybelongsTo

顺便说一句,你不一定要调用模型IngredientsRecipe,这仅仅是默认/惯例。

完成后,视情况将其视为hasMany,belongsTo或HABTM。

+0

非常感谢,我将开始研究它 – Olga 2010-10-29 10:12:01