доктрина 2 много для многих (Продукты – Категории)

Привет, у меня есть много-много отношений между Items (Products) и категориями, и я реализовал эти три объекта:

  1. Элемент объекта:

    /** * @Entity * @Table(name="items") */ use Doctrine\Common\Collections\ArrayCollection; class Item { /** * * @Id @Column(type="integer") * @GeneratedValue */ private $id_item; /** @OneToMany(targetEntity="ItemCategories", mappedBy="item") */ protected $categories; public function __construct() { $this->categories=new ArrayCollection(); } public function addCategory(ItemCategories $category){ $this->categories->add($category); } public function getCategories(){ return $this->categories; } } 

    2 Присоединиться к таблице (ItemCategories)

      /** * @Entity * @Table(name="item_categories") */ class ItemCategories { /** * * @Id @Column(type="integer") * @GeneratedValue */ private $id; /** * @Column(type="integer") */ private $id_item; /** * @Column(type="integer") */ private $id_category; /** @ManyToOne(targetEntity="Category", inversedBy="ItemCategories") * @JoinColumn(name="id_category", referencedColumnName="id_category") * */ protected $category; /** @ManyToOne(targetEntity="Item", inversedBy="$categories") * @JoinColumn(name="id_item", referencedColumnName="id_item") * */ protected $item; public function getCategory() { return $this->category; } public function setCategory($category) { $this->category = $category; } public function getItem() { return $this->item; } public function setItem($item) { $this->item = $item; } } 

    Таблица 3.Категории

      /** * @Entity * @Table(name="categories") */ class Category { /** * * @Id @Column(type="integer") * @GeneratedValue */ private $id_category; /** @OneToMany(targetEntity="ItemCategories", mappedBy="category") */ protected $ItemCategories; /** * * @Column(type="string") @var string */ } 

Теперь моя проблема в том, что я не знаю, как вставить элемент, используя СУЩЕСТВУЮЩИЕ категории. Я пытался:

  $item= new Entity\Item(); $itemCategoriesReferences=new Entity\ItemCategories(); $productCategoriesReferences->setItem($product); //get existing category from db using PkId $itemCategoriesReferences->setCategory($CategoryModel->getCategory(1)); $item->addCategory(itemCategoriesReferences); 

Я знаю, что это не имеет большого значения, но у меня нет другой идеи, поэтому, пожалуйста, помогите мне.

благодаря

Третий объект полезен, если вы хотите установить некоторые свойства отношения между категорией и элементом. Например, элемент «принадлежит» категории, элемент «предлагается» для добавления в категорию, элемент «ожидает» удаления из категории. Поскольку ваш ItemCategories не показывает ни одного из таких свойств, вам лучше всего делать это так, как указано в руководстве. Подробнее об этом читайте здесь: http://docs.doctrine-project.org/en/latest/reference/association-mapping.html#many-to-many-bidirectional

Во-первых, вы должны переименовать ItemCategories по ItemCategory, так как экземпляр этого элемента является только ссылкой между 1 элементом и 1 категорией.

Тогда это просто:

 $item = new Item(); $em->persist($item); $category = $em->getRepository('category')->find($id_category); $itemCategory =new ItemCategory(); $itemCategory->setItem($item); $itemCategory->setCategory($category); $em->persist($itemCategory);