0

following scenario:

Recipe hasMany RecipeItem
RecipeItem belongsTo Recipe, Ingredient

(Ingredient could be associated with hasMany RecipeItem, but I don't need that relation.)

so basically, a one sided HABTM without the join table, because my joining element (the RecipeItem) needs to have an additional attribute: count.

This article: http://book.cakephp.org/1.3/view/1650/hasMany-through-The-Join-Model describes how to either create/save all at once or completely separated. What I want is to create the one side (the ingredients) separated and the other side (the recipes) together with the association. When creating a new recipe, you could choose multiple ingredients.

How would you do this? Thanks.

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
Eike Cochu
  • 3,249
  • 7
  • 34
  • 57

1 Answers1

0

Honestly I think you should try to simplify your schema. It sounds needlessly complicated. Why do you need a record for both a RecipeItem and an Ingredient? They seem like they should be the same thing.

You can create additional fields in the join table so you don't need an extra relationship there. I think you should be able to just use Recipe HABTM Ingredient and be done.

Also, I tend to have trouble formatting my form data correctly for cake's automagic to work. For me, it is easier to format the join table records I want to save manually, and then save them explicitly with the join table model (after clearing the existing records). something like:

$toSave = array();
$this->loadModel('RecipesIngredients');
foreach($this->data['Ingredient'] as $ingredient) {
    $toSave[] = array(
        'recipe_id'=>$this->data['Recipe']['id'],
        'ingredient_id'=>$ingredient['id'],
        'count'=>$ingredient['count']
    );
}
$this->RecipesIngredients->deleteAll(array('recipe_id'=>$this->data['Recipe']['id']);
$this->RecipesIngredients->saveAll($toSave);
thefreeman
  • 1,035
  • 11
  • 13
  • Adding an extra attribute field to the join table was what I did first (which would have been perfect), but the default form input for HABTM is a multi select, how do I associate the attribute count to each selected item in the multiselect, as they are unordered? – Eike Cochu Aug 19 '12 at 14:36