2016-03-28 69 views
-1

继我的previous问题Ive有新问题。我有2个实体 - 作者和书籍,1位作者可能有很多书,但1本书只有1位作者。现在这本书还有创作日期。我可以告诉每个作者有多少书有这样的,Symfony2 Twig显示上个月的记录

Author Books 
Author1  5 
Author2  7 etc... 

但伴随着这种在同一个表,我需要证明单独如何每个作者的许多书在上个月加入,像这样:

Author Books Added in last month 
Author1  5   2 
Author2  7   3 etc.. 

在我的数据库,我得到它映射的书籍,这是获得所有书籍的作者所有作者的实体,像这样:

​​

所以我觉得应该有某种嫩枝datet的ime过滤器,只显示书籍,在上个月添加。我看到this问题和一些更多的在这里,但他们主要与格式化日期,而不是处理间隔。任何想法都会受到欢迎,谢谢。

EDIT 1个控制器代码

<?php 
namespace AB\ProjectBundle\Controller; 

use Symfony\Component\HttpFoundation\Request; 
use Symfony\Bundle\FrameworkBundle\Controller\Controller; 
use Doctrine\Common\Collections\Criteria; 
use Symfony\Component\HttpFoundation\Response; 
use AB\ProjectBundle\Entity\Book; 

class AuthorController extends Controller 
{ 
public function indexAction() 
{ 
    $em = $this->getDoctrine()->getManager(); 
$userid = $this->container->get('security.context')->getToken()->getUser()->getId();  
$entity = $em->getRepository('ABProjectBundle:Authors')->findBy(array('userid'=>$userid)); 

$books = $entity[0]->getBooks(); 

$criteria = Criteria::create() 
     ->where(Criteria::expr()->gte("datecreation", "2016-03-15")) 
     ->orderBy(array("datecreation" => Criteria::ASC)) 
     ->setFirstResult(0) 
     ->setMaxResults(20) 
     ; 

$filtered = $books->matching($criteria); 
$twig = 'ABProjectBundle::index.html.twig'; 
$paramTwig = array(
     'authors'  => $entity, 
     'filtered'  => $filtered, 
    ); 

    return $this->render($twig, $paramTwig); 
} 

回答

2

没有在树枝像这样的东西。您需要过滤您的收藏QueryBuilder/DQL(添加需要where)级别或使用Doctrine Collection Filtering

例如:

use Doctrine\Common\Collections\Criteria; 

// get $author 

$bookCollection = $author->getBooks(); 

$criteria = Criteria::create() 
    ->where(Criteria::expr()->gte("added_date", "2015-02-17")) 
    ->orderBy(array("added_date" => Criteria::ASC)) 
    ->setFirstResult(0) 
    ->setMaxResults(20) 
; 

$filteredAuthorBooks = $bookCollection->matching($criteria); 

那么这个传递给你的看法。尽量不要在模板中构建任何复杂的逻辑或过滤。最好在你的情况下,从joinAuthor查询中仅从DB获取仅需要的结果。

+0

我把它传递给视图的长度,但在视图中只获得零。如果我删除|长度,我为每个作者获得Doctrine \ Common \ Collections \ ArrayCollection @ 0000000023bf3ae5000000006ee44d9f。任何想法可能是什么? – Jack

+0

现在它说DateTimeType.php中的FatalErrorException第53行: 错误:在字符串上调用成员函数格式()。 DB中的added_date列的类型是Timestamp,将其更改为DateTime,但没有帮助。 – Jack

+0

将orm.yml文件中的列的类型更改为字符串,并解决了问题,但我不知道这是否是正确的方式。现在它正确地获得了第一作者在上个月创建的书的数量,并且它为该表中剩余的每个作者显示了相同的编号(( – Jack