I have 2 models which are connected via a HABTM association, in the same way that Recipes and Ingredients are associated in the cookbook.
I need to do the equivalent of finding all recipes which use a particular ingredient – how do I do that?
So basically, I’ll have ingredient_id, and I want to do something like:
$this->Recipe->find('all', array('conditions' => 'recipe uses this ingredient'));
I’d also like to retrieve a list of all ingredients which are used in at least one recipe.
When you use HABTM (
hasAndBelongsToMany) relationships in CakePHP, it creates a model by combining the names of both models in alphabetical order (reference). You can use that model to perform your query.Example:
In the example above, we’re using the IngredientsRecipe model which has 2 relationships, both
belongsTowith Ingredient and Recipe. Just in case a Recipe has multiple ingredients that match, we’re also grouping by the recipe ID.PS: You don’t need to define the relationship to IngredientsRecipe as long as you’ve defined the hasAndBelongsToMany relationship between Recipe and Ingredients. CakePHP will do the rest automatically.