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

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

    From $album->getTrackList() you will alwas get "AlbumTrackReference" entities back, so what about adding methods from the Track and proxy?

    class AlbumTrackReference
    {
        public function getTitle()
        {
            return $this->getTrack()->getTitle();
        }
    
        public function getDuration()
        {
            return $this->getTrack()->getDuration();
        }
    }
    

    This way your loop simplifies considerably, aswell as all other code related to looping the tracks of an album, since all methods are just proxied inside AlbumTrakcReference:

    foreach ($album->getTracklist() as $track) {
        echo sprintf("\t#%d - %-20s (%s) %s\n", 
            $track->getPosition(),
            $track->getTitle(),
            $track->getDuration()->format('H:i:s'),
            $track->isPromoted() ? ' - PROMOTED!' : ''
        );
    }
    

    Btw You should rename the AlbumTrackReference (for example "AlbumTrack"). It is clearly not only a reference, but contains additional logic. Since there are probably also Tracks that are not connected to an album but just available through a promo-cd or something this allows for a cleaner separation also.

提交回复
热议问题