如何使 doctrine2 实体一对多设置为“活动”的实体


How to get doctrine2 entity one to many entities that are set "active"

让我们假设博客文章和评论之间存在OneToMany教义2关联。博客文章可能有很多评论。每个评论都保持非活动状态,因此隐藏在前端,直到版主手动激活评论。

我现在正在尝试建立某种安全外观,以确保通过在树枝模板中的 {{blogpost.comments}} 变量循环访问它们来向视图提供"活动"注释。

尝试在博客文章实体中使用getComments((方法,我试图过滤ArrayCollection的评论,如下所示

/**
 * @return ArrayCollection
 */
public function getComments()
{
    return $this->comments->filter(function ($condition) {
        return $condition->getActive() === true;
    });
}

不幸的是,即使关系获取模式设置为"EXTRA_LAZY",Doctrine 也会完全加载每条评论。因此,这将以我想避免的方式影响应用程序的性能。

有没有办法全局隐藏非活动评论,或者我是否必须在每次访问视图中的 blogpost.comments 关系时过滤它们?

您应该使用集合的matching方法。如果未加载集合,它将向 SQL 查询添加筛选器,以仅加载所需的内容。如果您的集合已经加载,它将过滤 PHP 数组。

use Doctrine'Common'Collections'Criteria;
public function getComments()
{
    return $this->comments->matching(
        Criteria::create()->where(
            Criteria::expr()->eq('active', true)
        )
    );
}

更多信息请点击此处:http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/working-with-associations.html#filtering-collections

问候