简体   繁体   中英

ZF2 - Doctrine - Delete an entity persistent

started working with doctrine in ZF2 and need to delete an entity from persistence.

$result = $em->getRepository('zmpim\Entity\Collection')->findOneBy(array('id'=>$id));
    $products = $result->getProducts();
    $this->assertSame(1, count($products));
    $this->assertSame(3, count($products[0]->getFields()));
    $em->remove($result);
    $em->persist($result);
    $em->flush($result);

The example is in a unit test. I would expect, that the entity is deleted after it. But the entity and some OneToMany entities are still there.

cu n00n

What you are looking for is cascade={"remove"} . Take a look at this question:

Understanding Doctrine Cascade Operations

You define the cascade option in your association annotation of your entity like this:

/**
 * @ORM\OneToMany(/* ... */ cascade={"remove"})
 */

This works with every kind of association of course.

Doctrine Documentation:

http://doctrine-orm.readthedocs.org/en/latest/reference/working-with-associations.html#transitive-persistence-cascade-operations

In a separate unit test, you'd get the entities metadata to check for the cascade specification of the association by calling something like:

$mapping = $entityManager->getClassMetadata('zmpim\Entity\Collection')
    ->getAssociationMapping('products');
$this->assertTrue($mapping['isCascadeRemove']);

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