【问题标题】:Symfony2 - Listing Comments sorted in DESC order from Post entitySymfony2 - 列出从 Post 实体按 DESC 顺序排序的评论
【发布时间】:2014-08-04 19:07:38
【问题描述】:

我将评论设置为多对一/一对多到帖子。

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

我已经设置了一个查询以列出具有 DESC 顺序的单个帖子,但 cmets 仍显示为 ASC。

如何让 cmets 以 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
    );
}

【问题讨论】:

    标签: symfony post doctrine-orm comments


    【解决方案1】:

    好的,我需要再次查询 Comments 并在控制器中调用它。

    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();
    }
    

    【讨论】:

      【解决方案2】:

      你可以在注解中使用 order 指令

      /**
       * @ORM\OneToMany(targetEntity=Comment::class, mappedBy="Post", orphanRemoval=true)
       * @ORM\OrderBy({"createdAt" = "DESC"})
       */
      private $comments;
      

      【讨论】:

        猜你喜欢
        • 2016-03-18
        • 1970-01-01
        • 1970-01-01
        • 2012-12-14
        • 1970-01-01
        • 1970-01-01
        • 2016-08-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多