Symfony2 - 列表注释从Post实体以DESC顺序排序

时间:2014-06-14 09:39:58

标签: symfony post doctrine-orm comments

我将评论设置为ManyToOne / OneToMany to Posts。

我想以DESC的顺序显示帖子中的所有评论。

我已经设置了一个查询,用DESC订单列出单个帖子,但评论仍然显示为ASC。

如何以DESC顺序显示评论?它是否继承了帖子被列出的方式?

发布查询

public function findPostsBySlug($slug)
{
    return $this->createQueryBuilder('post')
        ->select('post')
        ->where('post.slug = :slug')
        ->setParameter('slug', $slug)
        ->orderBy('post.createdAt', 'DESC')
        ->getQuery()
        ->getSingleResult();
}

枝条

<h2>Comments</h2>
    {%  for comment in post.comments %}
        <article class="comment">
            <header>
                <p>
                <time datetime="{{ comment.createdAt | date('c') }}">{{ comment.createdAt | date }}</time>
                by {{ comment.author }}
                </p>
            </header>

                <p>{{ comment.body | nl2br }}</p><hr>
        </article>
    {%  endfor %}<br>

控制器

public function showAction($slug)
{
    $post = $this->getDoctrine()->getRepository('AcmeDemoBundle:Post')
        ->findPostsBySlug($slug);

    if (null === $post) {
        throw $this->createNotFoundException('Post was not found');
    }

    return array(
        'post' => $post
    );
}

1 个答案:

答案 0 :(得分:0)

好的想通了,我需要为评论做另一个查询并在控制器中调用它。

public function findCommentsForPost($postId)
{
    return $this->createQueryBuilder('comment')
        ->select('comment')
        ->where('comment.post = :post_id')
        ->setParameter('post_id', $postId)
        ->orderBy('comment.createdAt', 'DESC')
        ->getQuery()
        ->getResult();
}