Entity Setup
Doctrine 2 interprets a many-to-many relationship as an entity when it contains additional properties, becoming a separate entity with its own unique identifier. This is essential for tracking values associated with each relationship.
To implement this in your database, consider the following entity structure:
Product:
namespace Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Table(name="product") * @ORM\Entity() */ class Product { /** * @ORM\Id() * @ORM\Column(type="integer") */ protected $id; /** * @ORM\Column(name="product_name", type="string", length=50, nullable=false) */ protected $name; /** * @ORM\OneToMany(targetEntity="Entity\Stock", mappedBy="product") */ protected $stockProducts; }
Store:
namespace Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Table(name="store") * @ORM\Entity() */ class Store { /** * @ORM\Id() * @ORM\Column(type="integer") */ protected $id; /** * @ORM\Column(name="store_name", type="string", length=50, nullable=false) */ protected $name; /** * @ORM\OneToMany(targetEntity="Entity\Stock", mappedBy="store") */ protected $stockProducts; }
Stock:
namespace Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Table(name="stock") * @ORM\Entity() */ class Stock { /** * @ORM\Column(type="integer") */ protected $amount; /** * @ORM\ManyToOne(targetEntity="Entity\Store", inversedBy="stockProducts") * @ORM\JoinColumn(name="store_id", referencedColumnName="id", nullable=false) */ protected $store; /** * @ORM\ManyToOne(targetEntity="Entity\Product", inversedBy="stockProducts") * @ORM\JoinColumn(name="product_id", referencedColumnName="id", nullable=false) */ protected $product; }
This setup establishes three entities: Product, Store, and Stock. The Stock entity contains the amount field as an additional property, making it a Many-To-Many relationship with values.
The above is the detailed content of How to Implement a Many-to-Many Relationship with Extra Fields in Doctrine 2?. For more information, please follow other related articles on the PHP Chinese website!