开发者

How to set M:1 cascade to null using Doctrine2 associations?

Q a bit dubious, pardon that.

I want to remove a song enitity:

My 1:M associations works fine with a cascade = all. E.g. the ratings associated with the song can get deleted.

My M:1 I don't know how to do. Currently I'm setting those properties to null, then I persist those properties, then I remove the song. E.g the album and artist should stay, as it's associated to other songs.

Excerpt:

/**
 * OWNING SIDE
 * @var My\Entity\Album
 * @ManyToOne(targetEntity="Album", inversedBy="songs")
 */
private $album;

/**
 * INVERSED SIDE
 * @var Doctrine\Common\Collections\ArrayCollection
 * @OneToMany(targetEntity="Similar", mappedBy="songa", cascade={"all"})
 * @OrderB开发者_开发知识库y({"id" = "DESC"})
 */
private $similarsa;

I wish to keep using the association cascading and not on the db level. Any advice on using $em->remove($song) without the extra persisting of my M:1 to nulls?


I found it with the following:

In my song (parent) entity:

/** @PreRemove */
public function preRemove()
{
    $em = \Zend_Registry::get('doctrine')->getEntityManager();
    $em->getRepository('My\Entity\Similar')->removeSong($this);
    $em->getRepository('My\Entity\Rating')->removeSong($this);
}

Those methods (in repository) look like:

/**
 * Removes similars with song
 */
public function removeSong($song)
{
    $ratings = $this->getSong($song);
    foreach ($ratings as $rating) $this->getEntityManager()->remove($rating);
    $this->getEntityManager()->flush();
}

And in my Similar and Rating entites:

/** @PreRemove */
public function preRemove()
{
    $this->winner = $this->loser = null;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜