【问题标题】:How to get most recent entry with Repository如何使用存储库获取最新条目
【发布时间】:2015-07-27 14:53:23
【问题描述】:

我在使用 Doctrine2 时遇到了一件非常简单的事情,我无法弄清楚如何使用我的 findByDate 方法从存储库中检索实体的最后一个条目。 我无法在 Doctrine 文档或谷歌中找到如何做到这一点......

【问题讨论】:

  • 你也可以试试max(id)函数

标签: symfony doctrine-orm doctrine


【解决方案1】:

您必须执行按日期排序的查询,并返回第一个:

class MyEntityRepository extends EntityRepository
{
  function getLastEntity() {
    return $this->createQueryBuilder('e')->
       orderBy('e.date', 'DESC')->
       setMaxResults(1)->
       getQuery()->
       getOneOrNullResult();      
  }
}

【讨论】:

    【解决方案2】:

    试试:

    $date = new \Datetime();
    
    $em = $this->getDoctrine()->getManager();
    
    $lastEntity = $em
                     ->getRepository('MyBundle:Entity')
                     ->findBy(array('date' => $date->format('Y-m-d')));
    

    假设 MySQL 中的字段存储为date

    【讨论】:

    • 这是按日期过滤,但我认为 OP 想要获取最新条目(即按日期 DESC 排序时的第一个结果)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 2010-10-12
    • 2015-10-06
    • 1970-01-01
    相关资源
    最近更新 更多