Doctrine2 - 如何按月设置查询?

时间:2014-03-30 23:03:10

标签: symfony datetime doctrine-orm twig

一些快速上下文我在侧边栏中创建基于月/年的博客存档。我正处于需要显示该月帖子的位置。我需要一些帮助来创建此查询以传递到twig。

下面是原始问题的链接以及我到目前为止的设置,查询显然不正确(关于这篇文章的性质)并且可以使用一些帮助充实它。

通过向我展示如何在一个月内为帖子创建正确的查询并将其链接到树枝,向我展示如何完成这些最后的步骤,将不胜感激。

Symfony2 - Setting up a blog archive

到目前为止,这就是我所拥有的。

查询(需要帮助此部分 - 如何设置查询按月/年重复检索)

public function getPostsByMonth($year, $month)
{
    $qb = $this->createQueryBuilder('b')
    ->from('Blog', 'b')
        ->select('b')
    ->where('created BETWEEN :june AND :july')
        ->setParameter('june', $june->format('2013-June'))
        ->setParameter('july', $july->format('2013-July'))
        ???
}

路线

general_sym_project_archive:
 path:  /archive/{year}/{month}
 defaults: { _controller: GeneralSymProjectBundle:Blog:archive }

控制器

public function archiveAction($year, $month)
{
    $em = $this->getDoctrine()->getManager();

    $blogs = $em->getRepository('GeneralSymProjectBundle:Blog')
        ->getPostsByMonth($year, $month);

    if (!$blogs) {
        throw $this->createNotFoundException('Unable to find blog posts');
    }

    foreach ($blogs as $post) {
        $year = $post->getCreated()->format('Y');
        $month = $post->getCreated()->format('F');
        $blogPosts[$year][$month][] = $post;
    }



    return $this->render('GeneralSymProjectBundle:Default:archive.html.twig', array(
        'blogPosts' => $blogPosts,
    ));

Twig (需要按月将帖子链接到此树枝)

<h4>Archives</h4>
                    <ol class="list-unstyled">
                        <li><a href="{{ path('general_sym_project_archive', { 'year': '2013', 'month': '07'}) }}">July 2013</a></li>
                    </ol>

1 个答案:

答案 0 :(得分:2)

假设您的created字段是一个日期时间,并且您想要获取给定年份中给定月份的帖子,这应该有效:

public function getPostsByMonth($year, $month)
{
    $date = new \DateTime("{$year}-{$month}-01");

    $qb = $this->createQueryBuilder('b');
    $query = $qb
        ->where('b.created BETWEEN :start AND :end')
        ->setParameter('start', $date->format('Y-m-d'))
        ->setParameter('end', $date->format('Y-m-t'))
    ;
    return $query->getQuery()->getResult();
}