我正在尝试比较升级前后数据库上的数据,以便执行操作。
具体而言:
协会:艺术家ManyToMany原声音乐。
当我用唱片原声带删除一位艺术家时,我会检查该艺术家是否没有关联,如果为true,则删除该艺术家。
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());
}
}
}
}
查询findArtistByIdJoinSundtrack():
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,但数据库似乎没有更新。
为什么会发生这种情况?
我还清除了缓存好几次,以确保它不是问题所在!
请看一下我的答案。通常,不允许使用preUpdate侦听器更改相关实体。你的想法。。。
[…]事件postUpdate[…]在flush()之后调用。
不完全正确-postUpdate不是在flush()之后调用的,而是在内部调用的。
在EntityManager#flush()内部调用三个post[postUpdate、postRemove和postPersist]事件。更改在这里与数据库中的持久性无关。
(文档)