1

これまでに作成した M:N の関係は単純な中間テーブルであり、Doctrine がこのテーブルのエンティティを作成する必要はありません。

私は 2 つのエンティティ製品と成分を持っています。それらには、次のように Doctrine で簡単に説明できる M:N の関係があります。しかし、本当の問題はamount、関係にフィールドを保存する必要がある場合です(成分と量をリストする必要があります)。

これをどのように解決できますか?

class Product {
     //...
     /**
     * @var \Doctrine\Common\Collections\Collection
     *
     * @ORM\ManyToMany(targetEntity="MyBundle\Entity\Ingredient", inversedBy="product")
     * @ORM\JoinTable(name="product_ingredient",
     *   joinColumns={
     *     @ORM\JoinColumn(name="product_id", referencedColumnName="id")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="ingredient_id", referencedColumnName="id")
     *   }
     * )
     */
    private $ingredient;
     //...

class Ingredient {
    // ...
    /**
     * @var \Doctrine\Common\Collections\Collection
     *
     * @ORM\ManyToMany(targetEntity="MyBundle\Entity\Product", mappedBy="ingredient")
     */
    private $product;
    // ...
4

1 に答える 1

3

中間エンティティなしでは実際にそれを行うことはできません。そのため、ドクトリンのドキュメントでは、ManyToMany関係はまれであると述べられています。
また、これは最も簡単な方法です。RecipeItem情報Ingredientと金額を保存するエンティティを追加し、それを との関係にリンクするだけですManyToOneProduct

編集

例を提供するように求められたので:

class Product {
     //...
     /**
     * @ORM\OneToMany(targetEntity="RecipeItem", mappedBy="product")
     */
    private $ingredients;
     //...

class RecipeItem {
    // ...
    /**
    * @ManyToOne(targetEntity="Product", inversedBy="ingredients")
    **/
    private $product;

    /**
    * @ManyToOne(targetEntity="Ingridient")
    **/
   private $ingredient;

   /** 
    * @Column(type="decimal")
    **/ 
    private $amount;
}

class Ingredient {
    // Don't use bidirectional relationships unless you need to
    // it impacts performance
}

製品があれば、次のことが簡単にできます。

foreach($product->getIngridients() as $item){
    echo "{$item->getAmount()} of {$item->getIngridient()->getName()}";
}
于 2013-08-22T10:13:11.530 に答える