0

我有一篇文章和更多评论。我只想显示未标记为“已删除”的评论。我已经尝试过这样的事情,但我知道这是不正确的。

{% for comment in article.comments([{delete: false}])|slice(0, 5) %}
    // ...
{% endfor %}

我正在尝试接受 5 条未标记为“已删除”的评论。我该怎么做?

4

2 回答 2

1

你可以试试

{% for comment in article.comments|slice(0, 5) if not comment.deleted %}
    // ...
{% endfor %}

但我担心它可能会导致少于 5 条评论,因为它会在测试之前先切片,如果评论没有被删除。

相反,您最好在您的 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;
}

当然在 Twig 中调用它:

{% for comment in article.activeComments() %}
    // ...
{% endfor %}
于 2018-06-18T20:44:59.253 回答
0

我非常感谢您的支持,但我找到了另一种解决方案,并且在我看来看起来更好。

Article实体中,我创建了一个新方法:

public function getAvailableComments()
{
    return $this->getComments()->filter(function(Comment $comment) {
        return !$comment->isDeleted();
    });
}

此函数仅返回未删除的评论。(来源:https ://knpuniversity.com/screencast/collections/easy-collection-filtering )

注意:树枝与问题相同。

于 2018-06-19T16:08:46.530 回答