0

我正在尝试比较升级前后数据库上的数据,以便执行操作。

具体来说:

协会:艺术家多对多配乐。

当我通过唱片配乐删除艺术家时,我会检查该艺术家是否没有关联,如果为真则删除该艺术家。

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());

            }
        }
    }
}

查询 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();
}

当我运行查询以查看艺术家是否没有关联时,问题就出现了,实际上是在 postUpdate 中查询:

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

例如,如果一个艺术家与 id 为 71 的音轨只有一个关联,而我刚刚从 id 为 71 的音轨中删除了该艺术家,则查询不会返回空响​​应,而是返回一个只有 71 id 的元素音轨。

换句话说,尽管使用了在 flush() 之后调用的事件 postUpdate,但好像数据库没有更新。

为什么会这样?

我还多次清除缓存以确保不是问题所在!

4

1 回答 1

2

请在 此处查看我的答案。通常不允许使用 preUpdate 侦听器更改相关实体。你的想法 ...

[...] 事件 postUpdate [...] 在 flush() 之后调用。

... 不完全正确 - postUpdate 不是flush() 之后而是在内部调用的。

三个 post [postUpdate, postRemove, postPersist] 事件在 EntityManager#flush() 中调用。此处的更改与数据库中的持久性无关。

文档

于 2013-09-04T07:44:34.487 回答