从多对多关系的反面节省问题

时间:2011-09-07 00:55:08

标签: php doctrine-orm symfony

我有两个实体:AudioPlaylistAudioTrack

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;

我的问题是,当我调用$audioTrack->addAudioPlaylist($audioPlaylist)时,audioplaylist_audiotrack表格不会更新。我期待在表中添加一个新行,表示两个实体之间的关系。尽管$audioPlaylist->addAudioTrack($audioTrack)添加了一个新行,但一切正常。{/ p>

我确保坚持$audioTrack并刷新实体经理,但没有运气,所以我认为我的注释肯定有问题(我正在使用this example from the Doctrine docs)。任何想法?

1 个答案:

答案 0 :(得分:6)

这可能是因为您没有为反面设置cascade属性。您必须明确为Doctrine2定义cascading以保留任何相关实体。

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

在致电AudioTrack时,请务必同时将AudioPlaylist添加到AudioTrack::addAudioPlaylist()

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