【问题标题】:Symfony2 Twig show records for the last monthSymfony2 Twig 显示上个月的记录
【发布时间】:2016-03-28 08:49:13
【问题描述】:

在我的previous 问题之后,我遇到了一个新问题。我有 2 个实体 - 作者和书籍,1 个作者可能有很多书,但 1 本书只有 1 个作者。现在这本书也有创作日期。我可以显示每个作者有多少这样的书,

Author    Books 
Author1     5
Author2     7 etc...

但除此之外,我还需要在同一张表中分别显示每个作者在上个月添加了多少本书,如下所示:

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

在我的数据库中,我得到所有与书籍映射的作者实体,这是为作者获取所有书籍,如下所示:

<td>{{ author.books|length}}</td>

所以我认为应该有某种 Twig 日期时间过滤器,只显示书籍,在上个月添加。我在 SO 上看到了this 问题和更多问题,但它们主要与格式化日期有关,而不是处理间隔。欢迎任何想法,谢谢。

编辑 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);
}

【问题讨论】:

    标签: php symfony


    【解决方案1】:

    twig 中没有这样的东西。您需要在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);
    

    然后将其传递给您的视图。尽量不要在模板中构建任何复杂的逻辑或过滤。在您的情况下,最好的方法是在Author 查询中使用join 从数据库中获取只需要的结果。

    【讨论】:

    • 我将它传递给带有 |length 的视图,但在视图中只得到零。如果我删除 |length,我会为每个作者得到 Doctrine\Common\Collections\ArrayCollection@0000000023bf3ae5000000006ee44d9f。有什么想法吗?
    • 现在它在 DateTimeType.php 第 53 行中显示 FatalErrorException:错误:调用字符串上的成员函数 format()。 DB中我added_date列的类型是Timestamp,改成DateTime,但是没有用。
    • 将 orm.yml 文件中的列类型更改为字符串并解决了问题,但我不知道这样做是否正确。现在它正确地获取了第一作者在上个月创建的书籍数量,并且它为表中剩余的每个作者显示了相同的数量((
    • 它应该与 date_time 一起使用。如果没有看到您的实体和控制器代码,我就忍不住了。
    • entities 与上一个问题中的相同,但添加了新的属性 datecreation。一分钟添加控制器代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多