我有两个实体:产品和类别。这应该是多对多关系,因为每个类别可以有许多产品,并且每个产品可以属于许多类别。而且,我需要从我的产品访问类别,还需要知道该类别的产品。
这是我的代码。
在我的产品实体中:
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Category", cascade={"persist"})
*/
private $categories;
在我的类别实体中:
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Product", cascade={"persist"})
* @ApiSubresource
*/
private $products;
问题是,当我进行方案更新时,Doctrine会生成2个表:
category_product
和product_category
如何处理一张桌子?
答案 0 :(得分:2)
那很容易。
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Category", inversedBy="products")
*/
private $categories;
和
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Product", mapped_by="categories")
* @ApiSubresource
*/
private $products;
不要忘记在构造函数中进行初始化,并且cascade="persist"
是默认的AFAIK