[英]How to get doctrine2 entity one to many entities that are set “active”
让我们假设博客帖子和评论之间存在OneToMany doctrine2关联。 博客帖子可能有很多评论。 每个评论都保持不活动状态,因此隐藏在前端,直到主持人手动激活评论。
我现在正在尝试使用某种安全外观来确保只通过在twig模板中的{{blogpost.comments}}变量的循环中访问它们,只为视图提供“活动”注释。
试图在blogpost实体中使用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
问候
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.