Home >Backend Development >PHP Tutorial >How to Handle Many-to-Many Relationships with Extra Fields Using Doctrine 2\'s Link Table?
Doctrine 2 and Many-to-many Link Table with an Extra Field
This issue arises when attempting to create a database model with a many-to-many relationship that requires an additional field within the link table. Specifically, a stock-keeping table is required.
To resolve this, it is important to understand that such an association is not strictly a Many-To-Many relationship but rather a new entity, as it now possesses an identifier (relations to connected entities) and additional values.
The database model should be restructured as follows:
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\Id() * @ORM\ManyToOne(targetEntity="Entity\Store", inversedBy="stockProducts") * @ORM\JoinColumn(name="store_id", referencedColumnName="id", nullable=false) */ protected $store; /** * @ORM\Id() * @ORM\ManyToOne(targetEntity="Entity\Product", inversedBy="stockProducts") * @ORM\JoinColumn(name="product_id", referencedColumnName="id", nullable=false) */ protected $product; }
The above is the detailed content of How to Handle Many-to-Many Relationships with Extra Fields Using Doctrine 2\'s Link Table?. For more information, please follow other related articles on the PHP Chinese website!