开发者

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

开发者 https://www.devze.com 2023-04-02 18:43 出处:网络
I have two entities: AudioPlaylist and AudioTrack. AudioPlaylist.php: /** * @ORM\\ManyToMany(targetEntity = \"AudioTrack\", inversedBy = \"audioPlaylists\")

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?


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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消