Doctrine2: Best way to handle many-to-many with extra columns in reference table

后端 未结 14 1991
灰色年华
灰色年华 2020-11-22 10:44

I\'m wondering what\'s the best, the cleanest and the most simply way to work with many-to-many relations in Doctrine2.

Let\'s assume that we\'ve got an album like

14条回答
  •  抹茶落季
    2020-11-22 11:24

    The solution is in the documentation of Doctrine. In the FAQ you can see this :

    http://docs.doctrine-project.org/en/2.1/reference/faq.html#how-can-i-add-columns-to-a-many-to-many-table

    And the tutorial is here :

    http://docs.doctrine-project.org/en/2.1/tutorials/composite-primary-keys.html

    So you do not anymore do a manyToMany but you have to create an extra Entity and put manyToOne to your two entities.

    ADD for @f00bar comment :

    it's simple, you have just to to do something like this :

    Article  1--N  ArticleTag  N--1  Tag
    

    So you create an entity ArticleTag

    ArticleTag:
      type: entity
      id:
        id:
          type: integer
          generator:
            strategy: AUTO
      manyToOne:
        article:
          targetEntity: Article
          inversedBy: articleTags
      fields: 
        # your extra fields here
      manyToOne:
        tag:
          targetEntity: Tag
          inversedBy: articleTags
    

    I hope it helps

提交回复
热议问题