在Symfony2中構建博客,它有兩個實體:Blog
和BlogComment
(這是一個簡化示例)。 Blog
與BlogComment
有一對多關係。當發佈BlogComment
時,將屬性published
設置爲false
。在管理員批准BlogComment
後,它設置爲true
。在Symfony2中用聽衆計數緩存
我要創造我所有的Blog
-posts的概述,並顯示BlogComment
數量是published = true
和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);
}
}
}
}
它工作得很好,但是當我添加一個新的評論,它是不是在$Blog->getComments()
中的ArrayCollection呢。有沒有辦法來計算這個ArrayCollection的變化?
謝謝,您提出的第一個解決方案可能是最好的方法。我需要在其他一些更復雜的情況下使用相同的設置。第二種解決方案不起作用,就我所見,在樹枝中沒有計數過濾器,就像這樣工作。我儘量避免爲了計算而循環所有評論,這就是爲什麼我喜歡第一個解決方案:) – Thijs
抱歉,樹枝過濾器是長度不計算的。 :)但無論如何,我認爲它不工作,因爲你的發佈屬性(小枝不能算一個布爾值)。但是,如果您想停止循環實體來計算它們,我認爲最好的方法是使用您的博客存儲庫。我會編輯我的答案 –