2012-07-06 69 views
1

这是我DQL查询在MessageRepository: DQL查询,MAX功能和getSingleResult

public function getLastByIdAndByType($id_employee, $type) 
{ 
    $query = $this->_em->createQuery('SELECT MAX(m.sentAt), m.recipient, m.author, m.subject, m.body, m.type FROM MyBundle:Message m JOIN m.employee e WHERE e.id = :id_employee AND m.type = :type') 
    ->setParameter('id_employee', $id_employee) 
    ->setParameter('type', $type) 
    return $query->getSingleResult(); 
} </code> 

In my controller : $last_message=$em->getRepository('MyBundle:Message')->getLastByIdAndByType($id, $type);

在我看来html.twig {{ last_message.sentAt }}

返回错误:Item "sentAt" for "Array" does not exist

虽然

{{last_message.recipient}}的作品,但它是真的,我的所有邮件收件人是一样的。

我应该怎么做来呈现最新的日期与{{last_message.sentAt}}? 非常感谢!

回答

3

它看起来像你使用了错误的方法,如果我理解你想要达到的目标。

函数名去,我假设你想检索着被员工送往最近的消息信息。 对于这样的一个情况下,你想要做的是为了通过sentAt消息,并选择只是第一个。

你实际上做的是使用aggregate function,它会给你一个计算值实际上不是你的信息实体的一部分。

下面是一个如何做你想要的例子(请注意,因为我检索整个实体,你可以在你的视图中使用任何你喜欢的属性 - 为了性能的原因,你仍然可以选择在查询个人属性):

public function getLastByIdAndByType($id_employee, $type) 
{ 
    $query = $this->_em->createQuery('SELECT m FROM MyBundle:Message m JOIN m.employee e WHERE e.id = :id_employee AND m.type = :type ORDER BY m.sentAt DESC') 
         ->setMaxResults(1) 
         ->setParameter('id_employee', $id_employee) 
         ->setParameter('type', $type); 
    return $query->getOneOrNullResult(); 
} 

另外值得一提的是,你可以使用getOneOrNullResult因为我在这里做的,而不是仅仅getSingleResult避免抛出一个异常,如果没有找到记录。纯粹是一个选择的问题,但这意味着你在编码时有这种可能性。