Home >Database >Mysql Tutorial >How to Implement a Many-to-Many Relationship with Extra Fields in Doctrine 2?

How to Implement a Many-to-Many Relationship with Extra Fields in Doctrine 2?

Barbara Streisand
Barbara StreisandOriginal
2024-11-25 07:47:111079browse

How to Implement a Many-to-Many Relationship with Extra Fields in Doctrine 2?

Many-to-many link table with additional field in Doctrine 2

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn