Symfony 一次性细枝过滤器
我有一篇文章和更多的评论。我只想显示未标记为“已删除”的注释。 我试过这样的方法,但我知道那是不对的Symfony 一次性细枝过滤器,symfony,twig,twig-filter,Symfony,Twig,Twig Filter,我有一篇文章和更多的评论。我只想显示未标记为“已删除”的注释。 我试过这样的方法,但我知道那是不对的 {% for comment in article.comments([{delete: false}])|slice(0, 5) %} // ... {% endfor %} 我正在尝试接受5条未标记为“已删除”的评论。我怎么做?你可以试试 {% for comment in article.comments|slice(0, 5) if not comment.deleted %}
{% for comment in article.comments([{delete: false}])|slice(0, 5) %}
// ...
{% endfor %}
我正在尝试接受5条未标记为“已删除”的评论。我怎么做?你可以试试
{% for comment in article.comments|slice(0, 5) if not comment.deleted %}
// ...
{% endfor %}
但我担心它可能会导致少于5条评论,因为如果评论没有被删除,它将在测试之前首先切片
# src/AppBundle/Repository/ArticleRepository.php
namespace AppBundle\Repository;
class ArticleRepository extends \Doctrine\ORM\EntityRepository
{
public function getAllWithoutDeletedComments()
{
return $this->getEntityManager()->createQuery(
'SELECT a FROM AppBundle:Article a
JOIN a.comments c WITH c.deleted=0'
) ->getResult();
}
}
相反,您最好在articleRepository中编写一个自定义方法,该方法只提供未删除的注释
# src/AppBundle/Repository/ArticleRepository.php
namespace AppBundle\Repository;
class ArticleRepository extends \Doctrine\ORM\EntityRepository
{
public function getAllWithoutDeletedComments()
{
return $this->getEntityManager()->createQuery(
'SELECT a FROM AppBundle:Article a
JOIN a.comments c WITH c.deleted=0'
) ->getResult();
}
}
并从控制器中调用它:
$em = $this->getDoctrine()->getManager();
$articles = $em->getRepository('AppBundle:Article')->getAllWithoutDeletedComments();
或者向您的实体添加一种方法,用于过滤未删除的注释
public function getActiveComments($limit = 5)
{
$counter = 0;
$activeComments = [];
foreach($this->comments as $comment)
{
if(!$comment->getDeleted())
{
$activeComments[] = $comment;
if(++$counter == $limit)
{
break;
}
}
}
return $activeComments;
}
当然,把它叫做细枝:
{% for comment in article.activeComments() %}
// ...
{% endfor %}
我真的很感谢你的支持,但我找到了另一个解决方案,而且,在我看来,看起来更好 在
文章
实体中,我创建了一个新方法:
public function getAvailableComments()
{
return $this->getComments()->filter(function(Comment $comment) {
return !$comment->isDeleted();
});
}
此函数仅返回未删除的注释。(来源:)
注意:Twig与问题中的相同。该代码的结果是什么?尝试在
文章中用新方法编写过滤逻辑,然后切片这些结果。@JuanI.MoralesPestana没有抛出错误,没有任何更改。(我也删除了缓存)。我同意你@DarkBee的观点,但就我所知,这已经足够了:)