如何获得 doctrine2 实体一对多设置的实体 "active"

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

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

我现在正在尝试拥有某种安全外观,以确保只有 "active" 条评论会通过 {{blogpost.comments}} 循环访问它们来提供给视图树枝模板中的变量。

尝试在博文实体中使用 getComments() 方法,我试图像这样过滤评论的 ArrayCollection

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

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

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

您应该使用 collection 的 matching 方法。如果您的 collection 未加载,它将向 SQL 查询添加过滤器以仅加载您需要的内容。如果您的 collection 已经加载,它将过滤 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

此致