I've two entities: Product and Category. This should be many-to-many relationship, because each categories can have many products, and each products can belongs to many categories. And, I need to access Categories from my Product and also need to know the products of a category.
So here is my code.
In my Product Entity:
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Category", cascade={"persist"})
*/
private $categories;
In my Category Entity:
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Product", cascade={"persist"})
* @ApiSubresource
*/
private $products;
The problem is, when I do a scheme update, Doctrine generate 2 tables:
category_product
and product_category
How can I make it work with dealing with one table?
That's easy.
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Category", inversedBy="products")
*/
private $categories;
and
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Product", mapped_by="categories")
* @ApiSubresource
*/
private $products;
Don't forget to initialize in the constructor, and cascade="persist"
is default AFAIK