与Doctrine的多对多双向关系

时间:2015-02-11 10:41:01

标签: php symfony doctrine-orm

我在Doctrine中有多对多的双向关系。它将项目与类别相关联。问题是,在开始时我正在为项目分配一个类别,但是当我尝试更新项目的类别时,它会失败,并且有一个重复的主键。

以下是代码中可能有用的一些代码段:

/**
 * @ORM\Table(name="item")
 * @ORM\Entity(repositoryClass="SomeBundle\Entity\Repository\ItemRepository")
 *
 */
class Item
{
/**
     * @ORM\ManyToMany(targetEntity="Category", inversedBy="items",   cascade={"persist"})
     **/
    private $categories;
 public function __construct()
    {
        $this->categories = new \Doctrine\Common\Collections\ArrayCollection();
    }
/**
     * @param Item $item
     */
    public function addItem(Item $item)
    {
        $this->items[] = $item;
    }

/**
 * Category
 *
 * @ORM\Table(name="category", indexes={@ORM\Index(name="category_parent", columns={"parent_id"})})
 * @ORM\Entity(repositoryClass="SomeBundle\Entity\Repository\CategoryRepository")
 * @ORM\HasLifecycleCallbacks
 */
class Category
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
    * @ORM\ManyToMany(targetEntity="Item", mappedBy="categories", cascade={"persist"})
    * @ORM\JoinTable(name="item_category")
    **/
    private $items;

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

    /**
     * @param Category $category
     */
    public function addCategory(Category $category)
    {
        $this->categories[] = $category;
        $category->addItem($this);
    }

更新

 public function saveItem(Request $request)
    {
        $editMode = false;
        $itemId = $request->request->get('item_id');

        if (isset($itemId) && $itemId > 0) {
            $editMode = true;
        }

        $itemName = $request->request->get('itemName');
        $itemShortName= $request->request->get('itemShortName');

        $itemRepo = $this->getItemRepository();
        $item = $itemRepo->find($itemId);

        // get last Item Id
        if (!$editMode) {
            $newItem = new Item();
            $newItemId = rand(1000, 6000); // TODO
            $newItem->setId($newItemId);
            $newItem->setSection('ar');
            // by default the item is inactive
            $newItem->setActive(0);
        }

        //store the Item Type
        $itemType = new ItemType();
        $itemType->setTypeId($request->request->get('itemType'));

        if (!$editMode) {
            $itemType->setItemId($newItemId);
        }

        // store the data into the ItemTranslation
        if (!$editMode) {
            $newItemTranslation = new ItemTranslation();
            $newItemTranslation->setItemId($newItemId);
            $newItemTranslation->setLanguageId('1');
            $newItemTranslation->setItemName($itemName);
            $newItemTranslation->ItemShortname($itemShortName);
            $newItemTranslation->setTimestampAdd(new \DateTime());
            $this->em->persist($newItemTranslation);
        }

        //assign the respective Categories to the item
        $selectedCategoriesIds = $request->request->get('itemCategories');
        $categoryRepo = $this->getCategoryRepository();

        if (count($selectedCategoriesIds) > 0) {
            foreach ($selectedCategoriesIds as $selectedCategoryId) {
                $category = $categoryRepo->find($selectedCategoryId);
                if (is_object($item)) { //TODO
                    $item->addCategory($category);
                    $category->addItem($item);

                } else {
                    $newItem->addCategory($category);
                    $category->addItem($newItem);
                }

                if (!$editMode) {
                    $this->em->persist($newItem);
                }
            }
        }

        $this->em->flush();
    }

错误消息

An exception occurred while executing 'INSERT INTO item_category (item_id, category_id) VALUES (?, ?)' with params [2117, 1]:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '2117-1' for key 'PRIMARY'

**第二次更新**

我添加了这个      if(is_object($ item)){                 $本期特价货品> removeExistingCategories();             } 就在之前:

if (count($selectedCategoriesIds) > 0) {
            foreach ($selectedCategoriesIds as $selectedCategoryId) {
                $category = $categoryRepo->find($selectedCategoryId);

似乎它运行正常,但现在类别在UI中出现两次,尽管 item_category 表已正确填充。< / p>

好的,最后一个问题似乎已经排序了。我在itemsCategories迭代中犯了一个错误。 :)

1 个答案:

答案 0 :(得分:0)

尝试删除类别实体上的级联持久性...您应该只在关系的拥有方(项目中的项目)中执行此操作。