2012-03-26 12 views
0

我有两个模型,通过HABTM协会连接,就像食谱和食谱中的食谱相关联。Cakephp 2.0 - 如何检索使用特定配料的所有配方?

我需要做相当于找到所有使用特定配料的食谱 - 我该怎么做?

所以bascially,我就已经ingredient_id,我想要做的事,如:

$this->Recipe->find('all', array('conditions' => 'recipe uses this ingredient')); 

我也想取回其在至少一个配方中使用的所有成分的列表 - 可以有人帮我解决这个问题吗?

感谢您提供任何帮助 - 甚至可以链接到我可以阅读的内容,这些内容将对您有所帮助。

回答

1

当您使用HABTM(hasAndBelongsToMany)在CakePHP的关系,它按字母顺序(reference)两种型号的名称结合创建模型。您可以使用该模型执行查询。

实施例:

<?php 

$recipes = $this->Recipe->IngredientsRecipe->find('all', array(
    'conditions' => array(
     'IngredientsRecipe.ingredient_id' => 1 // This could also be an array of ingredients 
    ), 
    'group' => array('Recipe.id') 
)); 

在上面的例子中,我们使用具有2间的关系,既belongsTo用成分和配方的IngredientsRecipe模型。为了防止配方有多种配料匹配,我们也将配方ID分组。

PS:只要您已定义配方和配料之间的hasAndBelongsToMany关系,就不需要定义与IngredientsRecipe的关系。 CakePHP将自动完成剩下的工作。

+0

感谢您的帮助。我会放弃这个! – Sharon 2012-03-27 12:36:52

+0

我不明白为什么选中标记会出现在这个答案中,因为它与我的答案基本相同,但欢呼声让你的工作成功! :) – jeremyharris 2012-03-27 13:59:27

+0

对不起,杰里米,我刚刚攀登了第一名,说实话!我认为它已经到达第一,所以这是更快的答案。 – Sharon 2012-03-28 16:52:17

2

有没有简单的方法来做到这一点,但它可以通过几种不同的方式来完成。这可能是最简单的:定义一个函数,从连接表中抽取配方ID列表,然后在其上搜索。

所以,在成分模型:

function getRecipesFromIngredients($ingredient_ids) { 
    // IngredientsRecipe is the automatically created model 
    // Use what you defined in the 'with' key on your HABTM 
    // definition if you defined a 'with' key 
    $results = $this->IngredientsRecipe->find('all', array(
    'conditions' => array(
     'ingredient_id' => $ingredient_ids 
    ), 
)); 
    return Set::extract('/IngredientsRecipe/recipe_id', $results); 
} 

这将成为一个非常可测试的,可重复使用的功能。

然后在食谱控制器:

// would pull all recipes that have ingredients 1 and 2 
$recipes = $this->Recipe->find('all', array(
    'conditions' => array(
    'id' => $this->Recipe->Ingredient->getRecipesFromIngredients(array(1,2)) 
) 
)); 
+0

谢谢,这真的很有帮助! – Sharon 2012-03-27 12:37:04

相关问题