Clément Andraud
Clément Andraud

Reputation: 9269

Symfony Doctrine ManyToMany add custom join field

I have two entites : Cart and Item, the relation is configured with ManyToMany because a cart can have multiple items, and a items can be in multiple carts.

So I have a link table item_cart with item_id and cart_id.

How can I work with quantity with this ? For example if I need to add 800 items with id = 2 to the cart with id = 5 ?

Is this possible to add a field quantity in the link table ?

Thanks for help.

Upvotes: 3

Views: 2733

Answers (1)

Wilt
Wilt

Reputation: 44326

You can do this by making the relationship itself to an entity. This entity would be called CartItem or CartItemLink.

The association changes from ManyToMany between Cart and Item to two associations ManyToOne and OneToMany:

Cart - ManyToOne - CartItem - OneToMany - Item

Now you can add additional fields to your CartItem, like a $quantity field as mentioned in your question.

So this would look something like this:

The CartItem:

class CartItem {

    /** MANY-TO-ONE BIDIRECTIONAL, OWNING SIDE
     * @var Cart
     * @ORM\ManyToOne(targetEntity="Application\Entity\Cart", inversedBy="cartItems")
     * @ORM\JoinColumn(name="cart_id", referencedColumnName="id")
     */
    private $cart;

    /** MANY-TO-ONE BIDIRECTIONAL, OWNING SIDE
     * @var Item
     * @ORM\ManyToOne(targetEntity="Application\Entity\Item", inversedBy="cartItems")
     * @ORM\JoinColumn(name="item_id", referencedColumnName="id")
     */
    private $item;

    /**
     * @var int
     * @ORM\Column(type="integer", nullable=false)
     */
    private $quantity;

    //.. setters + getters
}

The Cart:

class Cart {

    /**
     * @var integer
     * @ORM\Id
     * @ORM\Column(type="integer", nullable=false)
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /** ONE-TO-MANY BIDIRECTIONAL, INVERSE SIDE
     * @var ArrayCollection
     * @ORM\OneToMany(targetEntity="Application\Entity\CartItem", mappedBy="cart")
     */
    private $cartItems;

    //.. setters + getters
}

The Item:

class Item {

    /**
     * @var integer
     * @ORM\Id
     * @ORM\Column(type="integer", nullable=false)
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /** ONE-TO-MANY BIDIRECTIONAL, INVERSE SIDE
     * @var ArrayCollection
     * @ORM\OneToMany(targetEntity="Application\Entity\CartItem", mappedBy="item")
     */
    private $cartItems;

    //.. setters + getters
}

I didn't add an id to CartItem because it can have either a composite key ($item_id + $cart_id) or a natural key and that I leave up to you.

Don't forget to initialize your $cartItems ArrayCollection inside the constructor of Item and Cart.

Upvotes: 7

Related Questions