doctrine 2 many to many (Products - Categories)

后端 未结 2 445
暖寄归人
暖寄归人 2021-01-26 09:05

Hi I have a many to many relation between Items(Products) and categories and I implemented using these three entities:

  1. Item Entity:

       /**
     * @         
    
    
            
相关标签:
2条回答
  • 2021-01-26 09:29

    A 3rd entity is only useful if you want to set some properties of the Relation between Category and Item. For example Item "belongs" to Category, item is "suggested" to be added to category, item is "pending" deletion from category. Since your ItemCategories doesn't show any of such properties you are really best of doing it the way the manual specifies. Read more about it here: http://docs.doctrine-project.org/en/latest/reference/association-mapping.html#many-to-many-bidirectional

    0 讨论(0)
  • 2021-01-26 09:39

    First, you should rename ItemCategories by ItemCategory, since an instance of this item is only the link between 1 item and 1 category.

    Then it's simple:

    $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);
    
    0 讨论(0)
提交回复
热议问题