Steven Mercatante
Steven Mercatante

Reputation: 25315

Problem saving from inversed side of many-to-many relationship

I have two entities: AudioPlaylist and AudioTrack.

AudioPlaylist.php:

/**
 * @ORM\ManyToMany(targetEntity = "AudioTrack", inversedBy = "audioPlaylists")
 * @ORM\JoinTable(name = "audioplaylist_audiotrack")
 *
 * @var ArrayCollection
 */
protected $audioTracks;

AudioTrack.php:

/**
 * @ORM\ManyToMany(targetEntity = "AudioPlaylist", mappedBy = "audioTracks")
 * 
 * @var ArrayCollection
 */
 protected $audioPlaylists;

My problem is that when I call $audioTrack->addAudioPlaylist($audioPlaylist), the audioplaylist_audiotrack table doesn't get updated. I'm expecting a new row to be added to the table signifying the relationship between the two entities. Everything works fine for the inverse though $audioPlaylist->addAudioTrack($audioTrack) adds a new row.

I'm making sure to persist $audioTrack and flush the entity manager, but no luck, so I assume there must be something wrong with my annotations (I'm using this example from the Doctrine docs). Any ideas?

Upvotes: 2

Views: 817

Answers (1)

kgilden
kgilden

Reputation: 10356

This is probably because you have not set the cascade property for your inverse side. You must define cascading explicitly for Doctrine2 to persist any related entities.

/**
 * @ORM\ManyToMany(targetEntity = "AudioPlaylist",
 *                     mappedBy = "audioTracks",
 *                      cascade = {"persist", "remove"})
 * 
 * @var ArrayCollection
 */
protected $audioPlaylists;

Make sure you also add your AudioTrack to AudioPlaylist as well, when calling AudioTrack::addAudioPlaylist():

public function addAudioPlaylist(AudioPlaylist $playlist)
{
    $this->getAudioPlaylists()->add($playlist);
    $playlist->getAudioTracks()->add($this);
}

Upvotes: 6

Related Questions