A Product may have zero or more Label. A Label can be assigned to zero or more Product. So, what’s the difference between mapping A and mapping B in Doctrine?
Mapping A (OneToMany – ManyToOne)
/**
* @ORM\Entity
* @ORM\Table(name="product")
*/
class Product
{
/**
* @ORM\OneToMany(targetEntity="Label", mappedBy="products")
*/
protected $labels;
}
/**
* @ORM\Entity
* @ORM\Table(name="label")
*/
class Label
{
/**
* @ORM\ManyToMany(targetEntity="Product", inversedBy="labels")
*/
protected $products;
}
Mapping B (ManyToMany – ManyToMany) documentation example
/**
* @ORM\Entity
* @ORM\Table(name="product")
*/
class Product
{
/**
* @ORM\ManyToMany(targetEntity="Label", mappedBy="products")
*/
protected $labels;
}
/**
* @ORM\Entity
* @ORM\Table(name="label")
*/
class Label
{
/**
* @ORM\ManyToMany(targetEntity="Product", inversedBy="labels")
*/
protected $products;
}
Your first example you try to match a ONE-TO-MANY relation to a MANY-TO-MANY relation. This will cause problems when trying to access the labels of a product. It will try to find the relation in a column in the label table. While a many-to-many relation should have an extra table that couples the two entities.
This is pure theoretically. I didn’t try it with real code, but I suppose Doctrine will throw an exception if you use the first example. I fact the first example should not be used.
If you’re not familiair with different types of relations read some articles about RDBMS:
http://en.wikipedia.org/wiki/Relational_model