我有两个实体: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)添加了新行,但对于逆函数一切正常。

我要确保坚持使用$audioTrack并刷新实体管理器,但是没有运气,所以我认为我的注释一定存在问题(我使用的是this example from the Doctrine docs)。有什么想法吗?

最佳答案

这可能是因为您尚未为反面设置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);
}

关于php - 从多对多关系的反面保存问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7327796/

10-11 06:08