简体   繁体   中英

Symfony ManyToMany delete record

I was trying to update a many to many relation between "book * <- -> * tag". For that, I first wanted to delete all current related tags of a book - to add afterwards again the changed /entered tags. Deleting all tags of a book is working, but when a tag has no more books mapped, it does not get deleted:

 // remove all tags from book
    foreach($book->getTags() as $tag)
    {
        $tag->removeBook($book);

        // remove tag if no books are mapped anymore
        if(count($tag->getBooks()) == 0) {
            $this->em->remove($tag);
        }
        $this->em->persist($tag);
    }
    $this->em->flush();

Why does it not delete the $tag (A tag entity object) if the count returns 0 (I already checked that it enteres the block.

The Owning Side of my relation is the "Tag"-Entity.

Clarifying your mixture:

remove an entity:

$this->em->remove($tag);

add / change an entity:

$this->em->persist($tag);

In both cases, you will need at the end:

$this->em->flush();

Perhaps try putting the persist operation in an else statement.

Although I haven't tested it, it seems to me that in this case, whether you delete a tag or not, you always end up persisting the tag again.

You are simply removing Tag if count($tag->getBooks()) == 0 :

$this->em->remove($tag);

and persisting it again:

$this->em->persist($tag);

else is required:

if(count($tag->getBooks()) == 0) {
    $this->em->remove($tag);
} else {
    $this->em->persist($tag);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM