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

后端 未结 14 1993
灰色年华
灰色年华 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:21

    I was getting from a conflict with join table defined in an association class ( with additional custom fields ) annotation and a join table defined in a many-to-many annotation.

    The mapping definitions in two entities with a direct many-to-many relationship appeared to result in the automatic creation of the join table using the 'joinTable' annotation. However the join table was already defined by an annotation in its underlying entity class and I wanted it to use this association entity class's own field definitions so as to extend the join table with additional custom fields.

    The explanation and solution is that identified by FMaz008 above. In my situation, it was thanks to this post in the forum 'Doctrine Annotation Question'. This post draws attention to the Doctrine documentation regarding ManyToMany Uni-directional relationships. Look at the note regarding the approach of using an 'association entity class' thus replacing the many-to-many annotation mapping directly between two main entity classes with a one-to-many annotation in the main entity classes and two 'many-to-one' annotations in the associative entity class. There is an example provided in this forum post Association models with extra fields:

    public class Person {
    
      /** @OneToMany(targetEntity="AssignedItems", mappedBy="person") */
      private $assignedItems;
    
    }
    
    public class Items {
    
        /** @OneToMany(targetEntity="AssignedItems", mappedBy="item") */
        private $assignedPeople;
    }
    
    public class AssignedItems {
    
        /** @ManyToOne(targetEntity="Person")
        * @JoinColumn(name="person_id", referencedColumnName="id")
        */
    private $person;
    
        /** @ManyToOne(targetEntity="Item")
        * @JoinColumn(name="item_id", referencedColumnName="id")
        */
    private $item;
    
    }
    

提交回复
热议问题