0
votes

I'm trying to compare data on the database before and after an upgrade, in order to perform the operations.

Specifically:

Association: Artist ManyToMany Soundtrack.

When I remove an artist by a record soundtrack, I check if that artist has been without associations, if true removes the artist.

public function postUpdate(LifecycleEventArgs $args)
{
    $entity = $args->getEntity();
    $em = $args->getEntityManager();

    if ($entity instanceof Soundtrack) {
        //$this->difference contains the difference between the artists before and the artists after the change.
        if(!empty($this->difference)) {
            foreach($this->difference as $m) {
                $art = $em->getRepository('AcmeUserBundle:Artist')->findArtistByIdJoinSoundtrack($m);
                var_dump($art->getId());

            }
        }
    }
}

query findArtistByIdJoinSoundtrack():

public function findArtistByIdJoinSoundtrack($id) {
    $qb = $this->createQueryBuilder('a');
         $query = $qb->select(array('partial a.{id}'))
                 ->innerJoin('a.soundtrack', 's')
                 ->where('a.id = :id')
                 ->setParameter('id', $id)
                 ->setMaxResults(1)
                 ->getQuery();

         return $query->getSingleResult();
}

The problem comes when I run a query to see if the artist has been without associations, in fact querying in postUpdate:

$em->getRepository('AcmeUserBundle:Artist')->findArtistByIdJoinSoundtrack($m);

for example, if an artist had only one association with the soundtrack with id 71 and I just removed from the soundtrack with id 71 that artist, the query does not return an empty response but returns an element soundtrack with just 71 id.

In other words it is as if the database is not updated despite having used the event postUpdate that is invoked after the flush().

Why does this happen?

I also cleared the cache several times to make sure it was not that's the problem!

1

1 Answers

2
votes

Please have a look at my answer here. Generally changing related entities is not allowed using a preUpdate listener. Your thought ...

[...] event postUpdate [...] is invoked after the flush().

... is not exactly correct - postUpdate is not invoked after flush() but inside.

The three post [postUpdate, postRemove, postPersist] events are called inside EntityManager#flush(). Changes in here are not relevant to the persistence in the database.

(documentation)