2016-03-28 95 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