我在Symfony2中构建一个博客,它有两个实体:Blog
和BlogComment
(这是一个简化的例子)。 Blog
与BlogComment
具有OneToMany关系。发布BlogComment
后,属性published
将设置为false
。管理员批准BlogComment
后,会将其设置为true
。
我想在我的所有Blog
个帖子中创建一个概述,并在两个单独的字段中显示BlogComment
和published = true
的{{1}}个数。可以将所有published = false
放在一个循环中并计算,但因为它可能是BlogComment
的非常大的概述 - 这不是我的首选选项。
我在Blog
创建了两个属性:Blog
和published_comments_count
。为了更新这些字段,我创建了一个unpublished_comments_count
的监听器:
BlogComment
它工作得很好,但是当我添加一个新注释时,它还不在class BlogCommentListener
{
public function onFlush(OnFlushEventArgs $args)
{
$em = $args->getEntityManager();
$uow = $em->getUnitOfWork();
$entities = array_merge(
$uow->getScheduledEntityInsertions(),
$uow->getScheduledEntityUpdates(),
$uow->getScheduledEntityDeletions()
);
foreach($entities as $entity){
if($entity instanceof BlogComment){
$Blog = $entity->getBlog();
$published_comments_count = 0;
$unpublished_comments_count = 0;
foreach($Blog->getComments() as $BlogComment){
if($BlogComment->getPublished()){
$published_comments_count++;
} else {
$unpublished_comments_count++;
}
}
$Blog->setPublishedCommentsCount($published_comments_count);
$Blog->setUnpublishedCommentsCount($unpublished_comments_count);
$em->persist($Blog);
$md = $em->getClassMetadata(get_class($Blog));
$uow->recomputeSingleEntityChangeSet($md, $Blog);
}
}
}
}
的ArrayCollection中。有没有办法计算此ArrayCollection中的更改?
答案 0 :(得分:1)
我认为不可能计算arrayCollection中的更改,但您可以通过为每个实体添加或删除1来更改逻辑:
class BlogCommentListener
{
public function onFlush(OnFlushEventArgs $args)
{
$em = $args->getEntityManager();
$uow = $em->getUnitOfWork();
$insertions = $uow->getScheduledEntityInsertions();
$deletions = $uow->getScheduledEntityDeletions();
foreach($insertions as $entity){
if($entity instanceof BlogComment){
$Blog = $entity->getBlog();
$Blog->setUnpublishedCommentsCount($Blog->getUnpublishedCommentsCount()+1);//Here the comment inserted must be unpublished
$em->persist($Blog);
$md = $em->getClassMetadata(get_class($Blog));
$uow->recomputeSingleEntityChangeSet($md, $Blog);
}
}
}
foreach($deletions as $entity){
if($entity instanceof BlogComment) {
$Blog = $entity->getBlog();
if ($entity->getPublished()) {
$Blog->setPublishedCommentsCount($Blog->getPublishedCommentsCount()-1);//Here the comment inserted must be unpublished
} else {
$Blog->setUnpublishedCommentsCount($Blog->getUnpublishedCommentsCount()-1);
}
$em->persist($Blog);
$md = $em->getClassMetadata(get_class($Blog));
$uow->recomputeSingleEntityChangeSet($md, $Blog);
}
}
}
奖励方面,我会让您更容易解决问题:在树枝模板中使用计数过滤器:
{% for blog in blogs %}
<li><h4>blog.title</h4>
<p>comments published : {{ blog.comments.published|count }}</p>
<p>comments non-published : {{ (not blog.comments.published)|count }}</p>
{% endfor %}