【问题标题】:How do I retrieve all recipes using a particular ingredient in Cakephp 2.0?如何在 Cakephp 2.0 中使用特定成分检索所有食谱?
【发布时间】:2012-03-26 20:37:13
【问题描述】:

我有 2 个模型通过 HABTM 关联连接,就像食谱和配料在食谱中关联的方式一样。

我需要找到所有使用特定成分的食谱 ​​- 我该怎么做?

所以基本上,我将拥有成分 ID,并且我想做类似的事情:

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

我还想检索至少在一个食谱中使用的所有成分的列表。

【问题讨论】:

    标签: cakephp cakephp-2.0


    【解决方案1】:

    没有简单的方法可以做到这一点,但可以通过几种不同的方式来完成。这可能是最简单的:定义一个从连接表中提取配方 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))
      )
    ));
    

    【讨论】:

    • 谢谢,这真的很有帮助!
    【解决方案2】:

    当您在 CakePHP 中使用 HABTM (hasAndBelongsToMany) 关系时,它会通过按字母顺序 (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')
    ));
    

    在上面的示例中,我们使用了有两个关系的成分配方模型,belongsTo 与成分和配方。以防万一食谱有多个匹配的成分,我们也会按食谱 ID 进行分组。

    PS:只要您定义了 Recipe 和 Ingredients 之间的 hasAndBelongsToMany 关系,您就不需要定义与 IngredientsRecipe 的关系。 CakePHP 会自动完成剩下的工作。

    【讨论】:

    • 感谢您的帮助。我会试试看的!
    • @Sharon - 关于@jeremyharris 留下的答案,我应该指出的一件事是您将执行两倍的查询。他建议在您的模型中放置的getRecipesFromIngredients 函数已经返回了您需要的所有内容,但他建议您然后使用从先前查询的结果中提取的recipe_id 列表再次在控制器中查询完全相同的数据.
    猜你喜欢
    • 1970-01-01
    • 2011-03-02
    • 2016-09-22
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    相关资源
    最近更新 更多