Symfony ManyToMany 生成 2 个表
Symfony ManyToMany generate 2 tables
我有两个实体:产品 和类别。这应该是多对多的关系,因为每个类别可以有很多产品,每个产品可以属于多个类别。而且,我需要从我的产品访问类别,还需要了解某个类别的产品。
这是我的代码。
在我的产品实体中:
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Category", cascade={"persist"})
*/
private $categories;
在我的类别实体中:
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Product", cascade={"persist"})
* @ApiSubresource
*/
private $products;
问题是,当我进行方案更新时,Doctrine 生成 2 tables:
category_product
和 product_category
如何让它与一个 table 打交道?
这很简单。
/**
* @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
我有两个实体:产品 和类别。这应该是多对多的关系,因为每个类别可以有很多产品,每个产品可以属于多个类别。而且,我需要从我的产品访问类别,还需要了解某个类别的产品。
这是我的代码。
在我的产品实体中:
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Category", cascade={"persist"})
*/
private $categories;
在我的类别实体中:
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Product", cascade={"persist"})
* @ApiSubresource
*/
private $products;
问题是,当我进行方案更新时,Doctrine 生成 2 tables:
category_product
和 product_category
如何让它与一个 table 打交道?
这很简单。
/**
* @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