Hugo Le Goff
Hugo Le Goff

Reputation: 75

Doctrine2 cascade default value

I'm actually learning Symfony3 and more precisely the Doctrine2 relation between objects and I was wondering if there is a default value for the cascade parameter when you don't explicite it.

I seen in tutorials when it's necessary to use the remove value that the parameter is not specified, but there is no explanation about this fact.

So I mean is this

/**
 * @ORM\ManyToOne(targetEntity="UTM\ForumBundle\Entity\UtmWebsiteTopics")
 * @ORM\JoinColumn(nullable=false)
 */
private $topic;

equivalent to that ?

/**
 * @ORM\ManyToOne(targetEntity="UTM\ForumBundle\Entity\UtmWebsiteTopics", cascade={"remove"})
 * @ORM\JoinColumn(nullable=false)
 */
private $topic;

Thank you for reading and I hope you'll be able to bring me an answer. :D

Upvotes: 1

Views: 1005

Answers (1)

Andrew Nolan
Andrew Nolan

Reputation: 2107

In short, those two snippets are not the same. If you were to want to delete a specific entity that has relations to others through FK, you would need to explicitly remove() the related entities to avoid Integrity Constraint Violations.

Examples of each

Not defining cascade={"remove"}

public function removeEntityAction($id)
{
    // Get entity manager etc....
    $myEntity = $em->getRepository("MyEntity")->findBy(["id" => $id]);

    foreach($myEntity->getTopics() as $topic) {
        $em->remove($topic);
    }

    $em->remove($myEntity);
}

Defining cascade={"remove"}

public function removeEntityAction($id)
{
    // Get entity manager etc....
    $myEntity = $em->getRepository("MyEntity")->findBy(["id" => $id]);

    $em->remove($myEntity);
}

Doctrine Cascade Operations

Doctrine - Removing Entities

Upvotes: 1

Related Questions