Doctrine2 @OrderBy 可以是计算字段吗? [英] Can Doctrine2 @OrderBy a calculated field?

查看:13
本文介绍了Doctrine2 @OrderBy 可以是计算字段吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I want to sort my model's associated ArrayCollection with a quotient, like this (I know the following code doesn't work):

/** 
 * @OneToMany (targetEntity="Review", mappedBy="product") 
 * @OrderBy ({"voted_up / voted_down" = "DESC"})
 */
protected $reviews;

Is something this possible directly in the model definition or do I need to simply use a sort() on the ArrayCollection when requesting the data?

解决方案

With Doctrine 2.1 you can do that directly in the model definition, but not with @OrderBy. You can define DQL snippets at model level, like stated in the 2.1 Beta release notes:

Named DQL Queries in Metadata: You can add dql queries in the mapping files using @NamedQueries(@NamedQuery(name="foo", query="DQL")) and access them through $em->getRepository()->getNamedQuery().

As such you can create your DQL query with the ORDER BY keywords, something like:

SELECT c.id, c.text, (c.voted_up / c.voted_down) AS sortkey FROM Comment c
ORDER BY sortkey DESC

So, I imagine you add this annotation to the model definition, something like:

/**
 * @Entity
 * @Table(name="comment")
 * @NamedQueries(@NamedQuery(name="sortedComment", query="SELECT c.id, c.text, (c.voted_up / c.voted_down) AS sortkey FROM Comment c ORDER BY sortkey DESC"))
 */
 class Comment {
     ...
 }

And then on your code call:

$em->getRepository("Comment")->getNamedQuery("sortedComment");

I didn't test this, but you get the idea.

这篇关于Doctrine2 @OrderBy 可以是计算字段吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆