2011-12-21 8 views
0

これについての議論が見つかりませんでしたので、これは本当に基本的なものでなければなりません。しかし、私はしばらくの間これを苦労してきました。doctrine2エンティティを更新する

this example(二重の一対多関係)のように実装された余分なフィールドと多少の多少の関係があります。これは、新しいエンティティを作成してデータベースに保存するときにうまく機能します。私は現在、編集機能を作成しようとしており、いくつかの問題に遭遇しました。

私の主なエンティティはRecipeと呼ばれ、Ingredientエンティティと多対多関係があります。 "amount"のような余分なフィールドは、RecipeIngredientエンティティにあります。レシピクラスには、成分配列にRecipeIngredientオブジェクトを追加するsetRecipeIngredientメソッドがあります。

Recipeクラスにいくつかの "clearRecipeIngredients"メソッドを作成すると、すべてのRecipeIngredientオブジェクトが削除されるはずですか?レシピを編集するときにこれを呼び出すと、データから新しいRecipeIngredientエンティティを作成し、新しいエンティティを作成するときのように材料アレイを作成します。私はカスケードの設定が正しく動作するように設定されていない可能性があると認めますが、次にそれを修正してみます。

関連するすべての例が優れています。

答えて

1

厳密に言えば、言及したように、多対多の関係はありませんが、1対多とそれに続く多対1の関係はありません。

質問については、レシピを編集するたびに一括「クリア」を実行しません。代わりに、紙ベースのレシピを編集する場合に実行される手順を模倣するための流暢なインターフェイスを提供します。

class Recipe 
{ 
    /** 
    * @OneToMany(targetEntity="RecipeIngredient", mappedBy="recipe") 
    */ 
    protected $recipeIngredients; 

    public function addIngredient(Ingredient $ingredient, $quantity) 
    { 
    // check if the ingredient already exists 
    // if it does, we'll just update the quantity 
    $recipeIngredient = $this->findRecipeIngredient($ingredient); 
    if ($recipeIngredient) { 
     $quantity += $recipeIngredient->getQuantity(); 
     $recipeIngredient->updateQuantity($quantity); 
    } 
    else { 
     $recipeIngredient = new RecipeIngredient($this, $ingredient, $quantity); 
     $this->recipeIngredients[] = $recipeIngredient; 
    } 
    } 

    public function removeIngredient(Ingredient $ingredient) 
    { 
    $recipeIngredient = $this->findRecipeIngredient($ingredient); 
    if ($recipeIngredient) { 
     $this->recipeIngredients->removeElement($recipeIngredient); 
    } 
    } 

    public function updateIngredientQuantity(Ingredient $ingredient, $quantity) 
    { 
    $recipeIngredient = $this->findRecipeIngredient($ingredient); 
    if ($recipeIngredient) { 
     $recipeIngredient->updateQuantity($quantity); 
    } 
    } 

    protected function findRecipeIngredient(Ingredient $ingredient) 
    { 
    foreach ($this->recipeIngredients as $recipeIngredient) { 
     if ($recipeIngredient->getIngredient() === $ingredient) { 
     return $recipeIngredient; 
     } 
    } 
    return null; 
    } 
} 

注:

は、私は以下のサンプル実装を提供し、あなたが適切に動作するために、このコードのセットアップ cascade persistorphan removalする必要があります。

もちろん、この方法をとると、すべての成分と量を一度に編集できるフルフォームが表示されることはありません。代わりに、各行に「削除」ボタンと、量を更新するための(単一フィールド)フォームをポップアップする「変更量」ボタンなど、すべての成分をリストする必要があります。