0

Im new to Symfony2 (having used symfony 1.x a couple years ago) and Im trying to understand how to handle entity relationships with Doctrine2. (Incidently, it would be nice if the Symfony2 book had more relationship examples instead of simply referring to the Doctrine2 docs :-)

So I have a simple product entity that I want to relate to multiple categories (i.e. single product can be in multiple categories). On the surface this looks like a one-to-many kind of relationship right, but Im thinking a relationship like that would be done via a join table in the database. So Im doing something like this instead:

class Product
{
  ....

  /**
   * @ORM\ManyToMany(targetEntity="Category");
   **/
  private $categories;

}

Doing a schema update does indeed create the join table in the database as expected. But Im wondering if Im wrong in making this a many-to-many instead ? I guess Im asking about best practices and how you would do this ? Can anyone advise and/or provide examples ?

Eno
  • 10,730
  • 18
  • 53
  • 86

2 Answers2

2

Your sentence "single product can be in multiple categories" is true but this one is true too : "multiple products can be in multiple categories". That's because you're not using the good sentences, which are:

  • "a category can have many products"
  • "a product can have many categories"

This means you have a many-to-many relationship.

If it were

  • "a category can have many products"
  • "a product can have only one category"

Then you'd have a one-to-many and a many-to-one relationship.

greg0ire
  • 22,714
  • 16
  • 72
  • 101
0

If you want a many to many relationship you will need an intermediate table

class Product
{
    /**
     * @ManyToMany(targetEntity="Categories")
     * @JoinTable(name="Product_Category",
     *      joinColumns={@JoinColumn(name="product_id", referencedColumnName="id")},
     *      inverseJoinColumns={@JoinColumn(name="Category_id", referencedColumnName="id")}
     *      )
     */
    private $categories;
}
SERPRO
  • 10,015
  • 8
  • 46
  • 63
  • 1
    You dont need to specify the join tables or columns unless you dont like the (sensible) defaults that Doctrine2 picks automatically. (See http://www.doctrine-project.org/docs/orm/2.0/en/reference/association-mapping.html#mapping-defaults) – Eno Nov 15 '11 at 12:55
  • Well yes, but I think it's more clear to see how the relation is make. :) – SERPRO Nov 15 '11 at 13:04
  • 1
    Love annotations but it gets distracting when reading code :-) – Eno Nov 15 '11 at 16:47