0

I need to model the following tables in Doctrine2:

  • Table 1. Items (products)
  • Table 2. Categories
  • Table 3. ItemsToCategories (id, item_id, category_id)

An item can be in many categories. A category can have many items. Restructuring the data is (currently) not an option and I did not design the schema.

What is the recommended way to model this many-to-many association with a join table. The documentation does not seem to cover this exact case and I'm keen to hear from others who have done something similar with Doctrine2 and / or Symfony (2.4)

codecowboy
  • 9,835
  • 18
  • 79
  • 134

1 Answers1

1

Create two entities: Item and Category:

<?php

namespace YourApplication\Bundle\DatabaseBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="Categories")
 */
class Category
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToMany(targetEntity="Item", inversedBy="categories")
     * @ORM\JoinTable(name="ItemsToCategories")
     */
    protected $items;

    public function __construct() {
        $this->categories = new \Doctrine\Common\Collections\ArrayCollection();
    }
}

<?php

namespace YourApplication\Bundle\DatabaseBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="Items")
 */
class Item
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToMany(targetEntity="Category", mappedBy="items")
     */
    protected $items;

    public function __construct() {
        $this->items = new \Doctrine\Common\Collections\ArrayCollection();
    }
}

Since a category owns the items and the items are owned by the categories, Category will be the owning side and Item will be the inverse side of the relationship.

rodrigorigotti
  • 234
  • 1
  • 8